app.CreatePerOwinContext(DataContext.Create);
I have the above line to create a data context this code came with project when i kick a new MVC 5 project. At the same time, i am using autofac to inject single instance per request in my dependency registrar.
builder.RegisterType<DataContext>().As<IDbContext>().InstancePerRequest();
What is the best way to use owin and DI container?
I have a DataContext class which has a static Method called Create as above and this break when I try to inject a logger in a database class for example.
I am also interested in a sample project if any , demonstrating DI and owin in the same project.
It is not necessary to use both OWIN and a DI container. I can understand your confusion, since the documentation on CreatePerOwinContext is very sparse, but the truth is that this feature is only implemented as a "poor man's DI", and should probably be replaced by a normal DI framework. Microsoft's Hao Kung, who is on the ASP.NET team says you are free to replace it with a proper DI framework.
If you're not fetching the instance created by the OWIN middleware, and instead injecting your context into your controllers, then you can safely remove it. Just remember to update the scaffolded controllers accordingly.
Related
I have the following code snippet in my application:
services.AddScoped<IMyInterface, MyService>();
services.AddSingleton<IYourInterface, YourService>();
Due to some environment initialization process, I have to be able to obtain the singleton instance of IYourInterface within Startup class to call the service to read a couple of configuration entries from a remote server and populate them. How can I achieve this goal considering the fact that I am using .Net Core's built-in DI framework?
The way to do this to create this instance manually up front as follows:
var service = new YourService();
services.AddScoped<IMyInterface, MyService>();
services.AddSingleton<YourService>(service);
Just as it is wise to separate the registration process from use (as the Microsoft.Extensions.DependencyInjection library correctly forces), this kind of separation is important between loading/building configuration and making the container registrations. Doing register-resolve-register is unsupported by libraries like MS DI, Autofac and Simple Injector, because it can lead to lots of complexity and subtle bugs.
I am currently using Simple Injector to resolve dependencies into my Asp.Net Web Api projects.
From the documentation you can configure it like that:
protected void Application_Start() {
// Create the container as usual.
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();
// Register your types, for instance using the scoped lifestyle:
container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);
// This is an extension method from the integration package.
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
container.Verify();
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
// Here your usual Web API configuration stuff.
}
The main points here are to register the Web Api controllers and set a custom dependency resolver.
However I've just read these article from Mark Seemann on how to configure dependency injection in Asp.Net Web Api:
Dependency Injection and Lifetime Management with ASP.NET Web API
Dependency Injection in ASP.NET Web API with Castle Windsor
From these articles, I've learnt that there is a better option than implementing IDependencyResolver to resolve Web Api dependencies.
This other option is to create an implementation of the IHttpControllerActivator that acts as an Adapter over the IoC Container.
Here is the implementation I've coded using SimpleInjector:
public class SimpleInjectorControllerActivator : IHttpControllerActivator
{
private readonly Container _container;
public SimpleInjectorControllerActivator(Container container)
{
_container = container;
}
public IHttpController Create(HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
request.RegisterForDispose(_container.BeginExecutionContextScope());
return (IHttpController)_container.GetInstance(controllerType);
}
}
and in the Application_Start method, I've replaced this line:
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
by this line :
GlobalConfiguration.Configuration.Services.Replace(
typeof(IHttpControllerActivator),
new SimpleInjectorControllerActivator(container));
I would like to know if the implementation of the IHttpControllerActivator is valid and also if this approach is valid and will work as good as the normal one ?
Yes, your implementation is valid.
Only be careful not to use both the SimpleInjectorWebApiDependencyResolver and the SimpleInjectorControllerActivator in the same application. Both start an ExecutionContextScope which could lead to having two scopes within the same web request, so they are mutually exclusive.
A general advantage of using a controller activator over the dependency resolver is that the dependency resolver contract forces the adapter to return null when a service can't be created. This is a very common problem that developers run into, and it often causes the confusing controller does not have a default constructor exception. This problem does not exist when using an IHttpControllerActivator, since the contract forces you to return a value or throw an exception.
The Simple Injector Web API integration project however, prevents this problem with dependency resolver, by never returning null (but throwing an exception instead) in case the requested service is an API controller (and thereby implicitly breaking the IDependencyResolver's contract).
An advantage of using the SimpleInjectorDependencyResolver is that it becomes easier to create message handlers that operate within the execution context scope, since you can trigger the creation of this scope by calling request.GetDependencyScope() method. With the current implementation, the scope just gets started at the time that the controller gets created, which is after you run the handlers. Changing this isn't that hard, but involves changing your controller activator and have an outermost handler that starts the execution context scope (or again falling back on a dependency resolver that manages the execution context scope).
One of the arguments of Mark Seemann is that it becomes hard to pass context around, which is a very valid point, as long as your components don't require this context during construction. But this is not a problem you'll experience when using Simple Injector, because there is an extension method that helps you with accessing the HttpRequestMessage. So although the IDependencyResolver abstraction isn't designed for getting the contextual information, there are ways to get this contextual information.
In the past we decided to go with an adapter for the IDependencyResolver, mainly because this was the common practice with all DI containers. I partly regret this decision, but using the SimpleInjectorDependencyResolver is now usually the easiest way of plugging in Simple Injector into Web API. We considered adding a SimpleInjectorControllerActivator as well, but this had no practical benefit for most users, while we still would had to document when to use what. So we decided to stick with the dependency resolver adapter; an adapter for the activator is easily created for anyone who needs it, as you can see.
For ASP.NET Core however, we went into a different direction, and as you can see in the documentation, the integration package actually contains a SimpleInjectorControllerActivator out of the box. In ASP.NET Core, the controller activator is the perfect interception point and due to the OWIN-like pipeline, a scope can be easily wrapped around a request. So with ASP.NET Core, the advised practice is to use the controller activator as interception point.
I've been following This MSDN tutorial about implementing OWIN to manage a single instance of DbContext and Identity UserManager classes.
It seems nice, but I'm also learning about Dependency Injection (I've been using Ninject) to get instances of objects.
I understand that OWIN creates and retrieves a single instance of an object per request and DI will return a new instance for every time that we require an object.
Do the two work together or share common features?
Should I be choosing one or the other or both together?
For example, should I be setting up an interface that has methods to return instances of my objects from the OWIN context and then injecting that into my controller?
The CreatePerOwinContext/Context.Get approach is not a general replacement for a regular IoC container and does not contain the [expected] features associated with dependency management - trivially, it provides no method for injecting dependencies. If anything, it is more akin to a basic Service Locator or [ab]use of the HttpContext.
Thus, while it can be used to establish an IoC container, it does not replace DI or an IoC container.
I'm using Ninject 3.0.1.10, MVC 5.0.0, FluentValidation 5.0 and finally FluentValidation MVC plugin library.
I'm trying to configure Ninject so that it injects a service into my AbstractValidator classes. I've read a lot of other answers about how to do this, but none have quite made sense to me. They all mention AssemblyScanner, which I can't find. They also mention accessing the IKernal from App_Start, but in my project App_Start does not have access to the IKernal because it's created inside of a NinjectWebCommon.cs file.
So I'm confused as to how to properly make this happen. Anybody have any clarity on this? Thanks.
You can access the IKernel configured by NinjectWebCommon.cs anywhere in your application. Of course, this usually is not recommended since it's a smell of Service Locator anti-pattern.
But there are cases where we can't escape from it, specially when mixing the frameworks and in your composition root, it's ok.
So, wherever you need, just use:
using Ninject;
//My class that will need access to the IKernel
var kernel = (new Bootstrapper()).Kernel;
The Bootstrapper class is initialized in App_Start.NinjectWebCommon before even the Application_OnStart runs. So it is safe to use even in Global.asax to obtain a reference to the IKernel. It remembers the kernel instance that was provided to it via a static variable inside the Bootstrapper class.
Hope that helps!
Using this sample project as a guideline, I am setting up a new project. My project will follow the same basic architecture, only in addition to an mvc project, I will also have a wcf web service project(or possibly servicestack.net)
Instead of using Unity for DI as in the sample, I am using Ninject. Currently I am configuring Ninject as follows to only instantiate one instance of Database factory per web request(and thus one datacontext class per request (using EF 4.1 code first btw))
kernel.Bind<IDatabaseFactory>()
.To<DatabaseFactory>()
.InScope(ctx => HttpContext.Current);
I am curious if this method is sufficient? Or would it be better to let the factory class handle the instantiation of datacontext per http request(and possibly per thread if I were design for non web based front-ends in the future)? If so, are there any examples out there of how to go about this?
Or is there a completely better solution to handle this?
You should use .InRequestScope() instead of .InScope(ctx => HttpContext.Current). It ensures that the appropriate scope is used depending on whether the instance is requested via WCF or via ASP.NET MVC. Unfortunately to take full advantage of this you'll have to use the current continous integration builds from http://teamcity.codebetter.com . See also
https://github.com/ninject/ninject.extensions.wcf
https://github.com/ninject/ninject.web.mvc