Recently I came across this discussion.
In ASP.NET WebAPI, when we need to integrate a custom inversion of control/dependency injection container, we need to go with two different strategies:
Implement IHttpControllerActivator, which is an extension point to fully control controller's life-cycle. That is, we can define how a controller is instantiated. At this point, we can resolve the controller using an inversion of control container and let it use its own dependency injection approach.
Implement IDependencyResolver, where we can define how to resolve dependency injections.
In my current projects I went the IHttpControllerActivator way, and since I'm using Castle Windsor as inversion of control container, I can fully control object life cycle from its container configuration, and I can decide how controllers are resolved, and the scope of its recursively-injected dependencies defining that they die once the controller ends its life (i.e. when the request ends).
While some of these features can be achieved with IDependencyResolver implementations, I feel that IHttpControllerActivator is the best way to integrate inversion of control and dependency injection in ASP.NET Web API, because I believe that I prefer to stay as abstract as possible and stick with Castle Windsor configuration model in terms of inversion of control and dependency injection.
The main drawback with the IHttpControllerActivator approach is you need to register all controllers in the container while IDependencyResolver still gives the responsibility of resolving the controller to ASP.NET Web API pipeline (for me, this hasn't been a big issue, I just used Castle Windsor's Classes.FromAssembly to configure all controllers deriving ApiController).
Do I ignore any other drawbacks that would make the IDependencyResolver approach more appropiate?
The IHttpControllerActivator approach primarily has an advantage over the IDependencyResolver approach because of the context provided, as excellently described in the following blog post: http://blog.ploeh.dk/2012/09/28/DependencyInjectionandLifetimeManagementwithASP.NETWebAPI/.
However, in most easier scenarios, it simply does not pay back the extra effort to manually register everything. Using the IDependencyResolver approach in many situations just 'does the trick'. Add good documentation and the larger day to day user base to that, and I myself would probably consider if I could manage using IDependencyResolver before considering IHttpControllerActivator.
Related
I'm moving from StructureMap 2.x to 3.x. One major change is that using ObjectFactory results in the following warning:
'StructureMap.ObjectFactory' is obsolete: 'ObjectFactory
will be removed in a future 4.0 release of StructureMap. Favor the
usage of the Container class for future
work'
So in most cases, the resolution is fairly easy: pass through IContainer as a constructor. Unfortunately this is not feasible for ASMX web serivces or attributes, both of which require a default constructor. That means I'm probably stuck with the Service Locator Pattern, property injection, or writing my own ObjectFactory implementation.
What's the preferred way to deal with this unfortunate problem?
Edit: It's worth mentioning that my container does an Assembly scan.
Per Jeremy Miller, himself:
Assembly scanning isn’t cheap and you (almost?) always wanna cache the
results. So, yeah, in that case you’re going to have to write your
own ObjectFactory. Someday all that bad old MS tech will go away.
So in this case, this implementation is what should be done.
The cleanest way I have seen to deal with this is to use .NET routing to take control of the entry point, then make a custom PageHandlerFactory implementation that takes the DI container as a dependency.
The custom page handler factory will then property inject the page/service after it is instantiated but before any of its events are called.
This is almost exactly the same way that IControllerFactory works with DI in MVC. In MVC, the container is injected into a custom IControllerFactory implementation at application startup, which effectively makes it a part of the application's composition root. In the case of ASP.NET, the IRouteHandler would effectively be part of the composition root.
I was unable to find a link to the source where I originally saw that implementation. But this one is pretty close. The primary difference is that one tries to use constructor injection, but the downside is that it requires full trust to do. I believe if you stick with property injection, you can do it with partial trust.
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.
Guys I need your help I am using Castle Project Windsor IoC container in my C# Winforms application. I have services classes which has DI by constructor passing in implementing Repositories. I used Windsor to register them all Component.Register(...etc but everytime I use my service class I am calling resolve. for example:
var employeeService = container.Resolve....etc
is there any other way not having to call resolve all the time?
in ASP.NET you can just register them all then set the Controller factory: ControllerBuilder.Current.SetControllerFactory(new WindsorIoCFactory());
with this I can just use my controllers(using services) directly without calling resolve. how do you do this in winforms?
You should use a Composition Root approach.
In short, you should use Resolve only once at the App-StartUp basically resolving the MainView and through that you should be able to obtain all views(most likely through a TypedFactory) and their dependencies with no explicit Resolve call.
Service locator approach, as per comment link, is a deprecable anti-pattern specially when Composition Root can be used instead.
On the windsor wiki you'll find a sample based on a Silverlight app, very close to a Winform scenario.
When using IoC for dependency injection the most recommended use is constructor injection (as told by many articles), my question is :
Is it better to inject using the constructor parameters or passing the IoC container through the constructor to inject the classes needed, and what is more useful for unit testing ?
Although passing the container through the constructor is better than making the container accessible as a singleton for the complete application, it is still a form of Service Locator (anti-pattern), and is not recommended. This has clear disadvantages:
It makes your code much harder to follow.
It makes it much less obvious when the Single Responsibility Principle is violated (since the class hides which things it depends on).
It makes it much hard to test, since you need to pass a configured container and you need to look in the code to see what the test need.
When requesting instances from the container directly from within every class, you will disable many features that IOC containers give you, because you don't allow the container to build up the object graph. Depending on the framework of choice, certain lifestyles and features like context based injection will not be usable.
All your tests use a container instance, making your tests come complex, and all your test have a dependency on the DI framework, which makes it very expensive to switch to another framework when needed.
Just inject the dependencies into the constructor, never* the container itself.
*Exception to this rule is when such class is located inside the appliation's Composition Root. In that case it's not considered to be the Simple Locator pattern, because that class is simply an infrastructure component.
Using constructor/property injection is better. When you pass the IOC container to the constructor you are no longer doing dependency injection and inversion of control. You are doing the Service Locator pattern. This means that classes no longer get their dependencies injected by the consumer, but they try are trying to fetch them. You are also probably tying your code to some particular DI framework.
I am designing some architectural changes into a legacy ASP.NET application. I prototyped some classes for dependency resolution that mimic the ASP.NET MVC's IDependencyResolver. I won't post because it is pretty much the same interface, but in other natural language.
I figured out it might be considered Service Location, which in turn is usually (not fully in some cases) condemned in favor of Dependency Injection. Nevertheless, I couldn't find any recommendation against the use of the ASP.NET MVC's dependency resolution implementation.
Is the ASP.NET MVC's IDependencyResolver considered an anti-pattern? Is it a bad thing?
If you look at the signature you will see that it's just a Service Locator with another name. Service Locator is an anti-pattern and I consider the relationship transitive, so I consider IDependencyResolver an anti-pattern.
Apart from that, the interface is also broken because it has no Release method.
I don't believe so... You can inject any IoC you want into ASP.NET MVC, which seems like a pretty good pattern to me.
Here's a blog post about injecting Unity into ASP.NET MVC 3.