What is alternate for CreatePerOwinContext in .net core 2.1 - asp.net-web-api

I had a webapi in which I was using app.CreatePerOwinContext in startup.cs file but I want to migrate that webapi to .net core 2.1. So I have stuck at this point as I can't fine any alternate for CreatePerOwinContext.
Here is my webapi code:
public static UserManager<IdentityUser> Create(IdentityFactoryOptions<UserManager<IdentityUser>> options, IOwinContext context)
{
var manager = new UserManager<IdentityUser>(new UserStore());
return manager;
}
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext<UserManager<IdentityUser>>(Create);
...
}
So how can I convert the above code in .net core 2.1?

That method was used as a service locator to load up dependencies and then access them throughout your code. Service location on its own is considered an anti-pattern, and is not recommended for use in the vast majority of real world situations.
Instead, people use IOC containers now to manage their dependency injection. In ASP.NET MVC Core, there's now a lightweight and "good enough" IOC container provided for you as part of the framework.
Microsoft provides an overview in this article, but the short version is that in your Startup.cs you register your dependency tree under ConfigureServices (usually using an extension method so Startup.cs doesn't get too large).
After you've registered your dependencies, you load them either through property injection, constructor injection, or method parameter injection. This results in cleaner code that is more maintainable than standard service location.
Edit:
If you truly insist on managing a service locator either because the technical debt is acceptable or because the business case warrants the current design, then I suggest you transition your work from OwinContext over to HttpContext.
In ASP.NET Core, you access the HttpContext by injecting the HttpContextAccessor into your class, and changing your OwinContext calls to pull from the key value store in HttpContext.
Instructions for injecting HttpContextAccessor can be found in this SO answer. Simply store KVPs using HttpContext.Current.Application["myObject"].
I don't recommend doing this, but I'm willing to share it because I understand the reality of deadlines vs the idealism of architecture.

Related

How to use memory caching in Asp.Net core 2 without constructor

In Asp.Net application(Class library project) , caching with using System.Runtime.Caching was working fine without use constructor.
protected ObjectCache ResponseCache
{
get
{
return MemoryCache.Default;
}
}
Now, I want to use same as in Asp.Net CORE application without constructor.
As Asp.Net CORE 2 is not supporting namespace System.Runtime.Caching and replace it Microsoft.Extensions.Caching.Memory
I use this MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions()) but it create always new object which clear all old cache memories.
Note: I'm looking solution for without defined constructor.
You have to implement it in ASP.NET Core way. That is, using dependency injection. You have to register the MemoryCache in the ConfigureServices method in the Startup class as:
services.AddMemoryCache();
then you need to inject the IMemoryClass in your controller to access it. You can check the docs for more details: Cache in-memory in ASP.NET Core
That way, you will not be worrying much on passing dependencies to the constructor since the DI container will handle it automatically.

Sample IoC, that is not DI

Dependency Injection is some form of Inversion of Control.
Could somebody please specify some other form of Inversion of
Control, that is not a dependency injection ?
Is there any java framework that is IoC container, but is not a DI
container ?
Which part of spring is IoC, but not a DI ?
Inversion of Control is the ability to allow a framework to run your custom code. As Martin Fowler says here:
Inversion of Control is a common phenomenon that you come across when
extending frameworks. Indeed it's often seen as a defining
characteristic of a framework.
So this is an example of Inversion of Control:
public class HomePage : Page
{
protected override void OnPageLoad(object sender, EventArgs e) {
// here your custom code
}
}
Here we have some custom class that 'by some convention' the framework (ASP.NET Web Forms in this case) picks up and it runs our custom code. The way it is done here is by inheritance and overriding virtual methods of the base class that the framework provides.
So this is an other example of Inversion of Control:
public class HomeController : Controller
{
public ActionResult Save(HomeSaveModel model) {
// here your custom code
}
}
Here we have our own custom controller where again the framework will call our code by some convention. Here we still use a base class given by the framework, but now the framework will call our Save action using reflection.
Inversion of control is all about hooking into framework code. Do note that in the examples above there is no dependency injection what so ever (nor is there Service Location).
Is there any java framework that is IoC container, but is not a DI container ?
The name "IoC container" is misleading, because those tools are meant to help you wire the dependency graphs in your application and do not help you wiring your code to a framework. IoC is a property of a framework; if it doesn't do IoC, it's not a framework: it's a library. Therefore "IoC containers" are libraries, not frameworks and they usually have no relationship with frameworks that we use (such as web frameworks such as ASP.NET).
So in this sense, there is no such thing as an "IoC container", since this is something that they can't do; by definition. In that context, your question stopped making sense :-), but to still answer it: no, "IoC containers" are always "DI containers" but never "IoC containers".

How to refactor out IDependencyResolver from MSDN tutorial

The tutorial by the msdn (source) recommends using an IDependencyResolver:
IDependencyResolver resolver = DependencyResolver.Current;
IDependencyResolver newResolver = new UnityDependencyResolver(container, resolver);
DependencyResolver.SetResolver(newResolver);
I was under the impression that IDependencyResolver does not properly manage object lifetime because it lacks a release method, and also that is conceptually a service locator anti-pattern (source).
How could I refactor this tutorial to not use IDependencyResolver?
Use Unity.Mvc3, there is a HierarchicalLifetimeManager that can manage lifetime for objects implementing IDispoable.
Its not an anti pattern if you resolve only at the composition root here, which basically with MVC is via constructor injection in the controller.
http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx
Note this doesn't have to be a custom controller factory you create, unity will inject automatically for you. See my code here:
http://completedevelopment.blogspot.com/2011/12/using-dependency-injection-with-mvc.html

MVC 3 And MEF and adding plug-ins to main application

I am a newbie to MEF and I am really mixed up! There are lot of useful articles out there and neat question and answers here in stackoverflow. I downloaded the example which #matthew-abbott has uploaded in his blog , but I dont know how to add new plug-ins or extension to extend the main web application, I mean like what you can see here.
Edited :
Also I use Entity Framework, Code First Approach and Unit of work for my data access layer application, what If my plug-ins needs data access and (I mean the plug-in has itself models) wants to use the DAL I created ? As you know every time the model changes, DbContext throws and error and tells re-create DB, Is there any way or other ORM which accepts extending DAL dynamically?
That particular example shows how we can integrate MEF with MVC3's new DependencyResolver which provides a service location mechanism for various extension points within the MVC architecture. There are a few other articles on my blog which detail more information about how a possible plugin architecture could work, these are available at:
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part One
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Two
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Three
There are also a host of fantastic articles, my recommendations would be to also read:
ASP.NET MVC and the Managed Extensibility Framework (MEF) by Maarten Balliauw
Defining Web-scoped parts with MEF by Tim Roberts
MVC is a very flexible architecture, there are a myriad of ways it can be extended, but because of the nature of how ASP.NET applications run in IIS, you need to consider part lifetime very carefully. As an example, controllers can only be used for one request, so you could would need to ensure that your controllers have a specific CreationPolicy. Tim Robert's article on Web-scoped parts is a particularly good read.
Hope that is enough to point you in the right direction.
Edit: Because of the modular nature that MEF provides, it is important to ensure that your different layers are decoupled. You've specified that you are using Entity Framework, but the reality is, EF should likely only be used in your data layer. Typically the MVC architecture would promote view models over domain models. To that end, it is probably useful to use something similar to the repository pattern to define, e.g. here is a mock UserRepository:
[Export(typeof(IUserRepository))]
public class UserRepository : IUserRepository
{
public IEnumerable<UserViewModel> GetUsers()
{
// Get values here from EF as domain models
// And return them as view models?
}
}
Which we can export and inject into a controller:
[ExportController("User"), PartCreationPolicy(CreationPolicy.NonShared)]
public class UserController : Controller
{
private readonly IUserRepository _repo;
[ImportingConstructor]
public UserController(IUserRepository repo)
{
if (repo == null)
throw new ArgumentNullException("repo");
_repo = repo;
}
public ActionResult Index()
{
var users = _repo.GetUsers();
return View(users);
}
}
This is just a really simple example, but like many IoC containers, MEF also supports dependency injection. As long as a part provides a suitable export, it can be imported (either through property injection, or constructor injection) into another part at composition time.
My recommendation would be against exposing EF to your views, as this makes them explicitly dependent on it. By taking care to decouple and only expose the right types at the right layers, you architecture will become a lot more robust, flexible and testable, which makes maintaining it, and updating it a lot easier. As another quick example, here is how we could test our controller:
[Test]
public void UserController_CreatesViewResult_WithListOfUsers()
{
var mock = new Mock<IUserRepository>();
mock.Setup(m => m.GetUsers()).Returns(new[] { new UserViewModel { Name = "Matt" } });
var controller = new UserController(mock.Object);
var result = controller.Index();
Assert.That(result is ViewResult);
// Other assertions.
}
Because I haven't tightly coupled EF to my view, my controller is a lot more testable, I can mock a suitable repository and test where I need to.
The important thing is planning your architecture.

ASP.NET MVC Views Dependency Injection without DependencyResolver?

Is it possible to inject dependencies into an MVC ViewPage (must support layout pages) without using DependencyResolver?
I would rather not use DependencyResolver at all (I had major problems when injecting NH sessions into ActionFilters in the past (leaking all over the place)). However, I'm not sure if there is an alternative?
The other complexity I have is that the DependencyResolver needs to be tenant aware (each tenant has its own (StructureMap) container). I'm currently doing this by passing in a lazy instance of my tenant container resolver (seems this is necessary otherwise the resolver is cached):
public SmDependencyResolver(Func<ISiteContainerResolver> containerResolver)
{
this.containerResolver = containerResolver;
}
public object GetService(Type serviceType)
{
var container = containerResolver().Resolve();
If I end up using DependencyResolver should I ditch my StructureMap controller factory since it looks like DependencyResolver handles this too?
Thanks
Ben
Given that the DependencyResolver is used by so many aspects of the ASP.NET MVC framework for dependency injection your life will be easier if you use it - as you say it means you don't need your own versions of things like the controller factory.
That said, the framework is very flexible and it is always open for you to plug in your own version of things - I just prefer to create as little of my own code as possible on the KISS principle.

Resources