So far in reading about possibilities of injection to custom membership providers, I've found two possible ways to do it:
One is the following: http://bugsquash.blogspot.com/2010/11/windsor-managed-membershipproviders.html
Here the author basically suggests to register your custom provider and then have a rather questionable windsor adapter for membership (I don't really like the way in which it instances your provider using a container it gets from HttpApplication, which it ultimately wraps with the windsor adapter).
This is another, similar option: http://code.google.com/p/webdotnet/source/browse/trunk/Steeg.Framework/Web/Security/MemberShipProvider.cs?r=2
Where you just override Initialize() and manually instance the dependencies there. At least in the first one, you don't need to instance dependencies by hand (other than the provider itself).
There are then a few which also suggest using a service locator of some kind (MVC's or otherwise)
Then I've come across ninject injecting dependencies to properties on Membership.Provider rather easily with something like _kernel.Inject(Membership.Provider). This is much closer to what I want, keeping the composition root concept which drew me to using DI in the first place.
How can I achieve a similar result using castle?
Update: apparently this has issues with lifecycle management.
Inject repository to custom membership provider with Ninject
Should I go for option #1 then? At least with that I instance the provider myself. So lifecycle management shouldn't be an issue.
I wouldn't go with implicit property injection, since the container will skip over the property if the type is not (correctly) registered, instead of failing fast (more info here). Instead I would use the Service Locator, but write a wrapper membership provider that does not contain any logic, but simply requests a membership provider from the service locator and calls that implementation. Jonas Gauffin wrote such a thing for MVC (using the DependencyResolver service locator), which is quite nice (also available on NuGet), but it is easy to do yourself.
Although the use of the service locator is considered an anti-pattern, please remember that the membership model must be configured through the web.config and this part of the system does not use the DependencyResolver.Current itself. Also writing such a DependencyResolverMembershipProvider is just a bit of mechanics and can be considered part of the composition root, not of the application. Calling the container inside your composition root is not a problem.
Related
I have a series of core services that I want to configure with Castle Windsor, things like Logging, Caching, Email config, etc. Making these services easily configurable by an app.config change would be a great boon (e.g. even just for development/testing it's great to be able to tell the app to route all the email traffic through some other mechanism than the actual mail server).
Two questions:
Many of the classes that need access to these services all inherit from an abstract base class (contains core logic used by all subclasses) so it would seem ideal to inject the core services into this base class somehow so that all the children would inherit the references to the services. Note these subclasses also all implement an Interface so that may be the better path to go down?
I also have a scenario where unrelated objects in other assemblies also need to be able to tap into the core services. These objects are not instantiated by me but by other libraries (I'm implementing the interface of some 3rd party library that then uses my implementation in its framework). If I need access to email or logging or some other core service in this code, how do I get a reference?
I hope that makes sense, thank you.
Regarding your first point, use property injection.
You have two choices for injecting dependencies; via the constructor or via properties. Since you don't want to pass dependencies down the constructor chain, the only other way is via property injection. This has the advantage that if a base class need to add/remove/change a dependency, it doesn't affect everything that inherits from it.
Some folks (myself included) shy away from property injection because it makes dependencies non-obvious and can imply that they are optional. This can make unit testing (you're doing that, right?) difficult because you have to inspect the class to see what dependencies are needed. If they were in the constructor, it'd be obvious.
However, if you can make sane null-object implementations of your services so that they are optional, or the unit-testing implications don't phase you, then this is a good route to go down.
As to your second question, if you can't control how the class gets created, you can't expect Windsor to supply any of its dependencies. At best, you can resolve the dependencies individually (i.e. call container.Resolve<IYourDependency>()) and assign them to the properties of your implementation.
I might be describing this wrong, but here's my dilemma, I have a series of interfaces, like IBreadcrumbRetriever. Their implementations are radically different depending where on my site they are, which I'm using HttpContext.Current.Request.Path to determine.
So inside my concrete class I'm right now have several if statements that determine what items to return (for simplicity sake, let's say List<string>). This is a code smell to me.
What I would really like, is somehow, and I feel as if IoC and Castle Windsor can help me out here, is determine if the user hitting the page meetings the certain conditional and bind the correct container to that. So I'd have something like
if (HttpContext.Current.Request.Path == some condition)
IBreadcrumbRetriever is ImplementedBy IsInProductAreaRetriever
Is this a good idea? If so how would I do this? Or do I create like a breadcrumb factory class and use the ".DependsOn(HttpContext.Current.Request.Path)" extension to achieve what I'm doing?
It depends on whether your app architecture is fit for dependency injection.
Not familiar with Castle Windsor but generally speaking, if a dependency can't be resolved at the composition root (app startup) I see nothing wrong with injecting a factory implementation that works with current http context.
For example, in an ASP.NET application your composition root would be in global.asax. There you could bind some IBreadcrumbRetrieverFactory to a BreadcrumbRetrieverFactory implementation. newing up classes that aren't part of the core framework (and a few that are) is generally a sign of a missed DI opportunity (and of tight coupling).
IoC containers and DI aren't a silver bullet: Depencency Injection is merely a design pattern (think constructor injection, constructors that only assign private readonly fields - the type's dependencies), and IoC containers (all of them) are nothing but tools to facilitate the wiring-up of dependencies with concrete implementations. With that in mind, there's nothing Castle Windsor will do that you can't achieve with poor man's DI: the key is all about pushing the instantiation of dependencies as early as possible - namely, at the application startup, the composition root.
When a dependency is "dynamic", like, when there's a logic that determines whether the implementation of ISmurf should be HappySmurf or GrumpySmurf, the best thing to do is, IMHO, to inject a ISmurfFactory dependency instead of a ISmurf, and push the factory's wiring-up to the composition root.
Imagine you have an application with several hundreds of classes implementing dozens of "high level" interfaces (meaning component level). Is there a recommend way of doing dependecy injection (like with unity). Should there be a "general container" that can be used for bootstrapping, accessible as a Singleton? Should a container be passed around, where all instances can RegisterInstance? Should everything be done by RegisterType somewhere in the startup? How can the container be made accessible when needed. Constructor injection seems false, controverse of being the standard way, you have to pass down interfaces from a component level to the very down where it is used right on startup, or a reference is hold ending up in a "know where you live" antipattern.
And: having a container "available" may bring developers to the idea of resolving server components in client context. how to avoid that?
Any discussion welcome!
edit for clarification
I figured out a somewhat realworld example to have a better picture of what problems i see.
lets imagine the application is a hifi system.
the system has cd player (integrated in a cd-rack) and
an usb port (integrated in an usb rack) to play music from.
now, the cd player and the usb port shall be able to play mp3 music.
i have an mp3 decoder somewhere around, which is injectable.
now i start the hifi system. there is no cd inserted yet and
no usb stick pluged in. i do not need a mp3 decoder now.
but with constructor injection, i have to already inject
the dependency into the cd rack and the usb rack.
what if i never insert a mp3 cd or an mp3 usb stick?
shall i hold an reference in the cd rack, so when an mp3 cd
is inserted, i have a decorder on hand? (seems wrong to me)
the decoder is needed in a subsystem of the cd rack, which
is only started if a mp3 gets inserted. now i have no container
in the cd rack, what about constructor injection here?
First of all, Dependency Injection is a design pattern that does not require a container. The DI pattern states:
Dependency injection is a software design pattern that allows a choice of component to be made at run-time rather than compile time
Take for example Guice (java dependency injection framework), in Java Guice is a DI framework but it is not a container itself.
Most of the DI tools in .Net are actually containers, so you need to populate the container in order to be able to inject the dependency
I do not like the idea to have to register every component every time in a container, I simply hate that. There are several tools that help you auto register components based on conventions, I do not use Unity, but I can point you for example to Ninject or AutoFac
I am actually writing a small utility to auto register components based on conventions using practically any DI tool, it is still in dev phase
About your questions:
Should there be a "general container" that can be used for bootstrapping, accessible as a Singleton?
The answer is yes, (there's a tool to abstract the DI tool used, it is called ServiceLocator) that's how DI tools work, there is a static container available to the application, however, it is not recommended to use it inside the domain objects to create instances, that's considered an anti-pattern
BTW I have found this tool really useful to register components at runtime:
http://bootstrapper.codeplex.com/
Should a container be passed around, where all instances can RegisterInstance?
No. that would violate the law of Demeter. If you decide to use a container is better to register the components when the application starts
How can the container be made accessible when needed
Well using the Common Service Locator you could use it anywhere in your application, but like I said, it is not recommended to use it inside the domain objects to create the required instances, instead, inject the objects in the constructor of the object and let the DI tool to automatically inject the correct instance.
Now based on this:
Constructor injection seems false, controverse of being the standard way, you have to pass down interfaces from a component level to the very down where it is used right on startup, or a reference is hold ending up in a "know where you live" antipattern
Makes me think that you are not writing unit tests heavily for your application which is bad. So my suggestion is, before choosing between which DI tool you are going to use, or before taking all the answers you get to this question into consideration, refer to the following links which are focus on one thing: Write clean testable code, this is by far the best source you could get to answer yourself your own question
Clean Code talks:
http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded
http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded
Articles
http://misko.hevery.com/2010/05/26/do-it-yourself-dependency-injection/
http://misko.hevery.com/code-reviewers-guide/
Previous link in PDF http://misko.hevery.com/attachments/Guide-Writing%20Testable%20Code.pdf
The following links are super highly recommended
http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/
http://www.loosecouplings.com/2011/01/how-to-write-testable-code-overview.html
First, there is the Composition Root pattern, you set up your dependencies as soon as possible, Main() in desktop, global.asax/app_start in web. Then, rely on constructor injection as this makes your dependencies clear.
However, you still need something to actually RESOLVE dependencies. There are at least two approaches known to me.
First one consist in using the Service Locator (which is almost equal to making the container a singleton). This is considered an antipattern for a lot of people, however it just works great. Whenever you need a service, you ask your container for it:
... business code...
var service = ServiceLocator.Current.GetInstance<IMyService>();
service.Foo();
Service Locator just uses a container you set up in the Composition Root.
Another approach consist in relying on object factories available as singletons with the container injected into them:
var service = IMyServiceFactory.Instance.CreateService();
The trick is that implementation of the factory uses the container internally to resolve the service. However, this approach, with an additional factory layer, makes your business code independent and unaware of the IoC! You are free to completely redesign the factories to not to use IoC internally and still maintain every single line of business code.
In other words, it's just a trick then to hide the container/locator behind a factory layer.
While tempted to use the former approach (rely directly on the locator) I prefer the latter. It just feels cleaner.
I wonder if there are other viable alternatives here.
Should a container be passed around
No, since this leads to the Service Locator anti-pattern.
where all instances can RegisterInstance
Services should be registered in the start-up path of the application, not by types themselves. When you have multiple applications (such as web app, web service, WPF client), there will often be a common bootstrapper project that wires all services together for shared layers (but each application will still have its unique wiring, since no application behaves the same).
Should everything be done by RegisterType somewhere in the startup
Yes, you should wire everything up at start-up.
How can the container be made accessible when needed.
You shouldn't. The application should be oblivious to the use of a container (if any container is used, since this is optional). If you don't do this, you will make a lot of things much harder, such as testing. You can however, inject the container in types that are defined in the startup path of the application (a.k.a. the Composition Root). This way the application keeps clean from knowing anything about the container.
Constructor injection seems false, controverse of being the standard way
Constructor injection is the prefered way of injecting dependencies. However, it can be challanging to refactor an existing application towards constructor injection. In **rare* circumstances where constructor injection doesn't work, you can revert to property injection, or when it is impossible to build up the complete object graph, you can inject a factory. When the factory implementation is part of the composition root, you can let it depend on the container.
A pattern I found very useful, that can be built on top of the Dependency Injection pattern and the SOLID design principles, is the command / handler pattern. I found this a useful pattern in smaller apps, but it will shine when applications get big, such as enterprise applications.
now i start the hifi system. there is no cd inserted yet and no usb
stick pluged in. i do not need a mp3 decoder now.
This seems like a perfect fit for Setter injection (=property injection in C#). Use a NeutralDecoder or NullDecoder as a default and inject an Mp3Decoder when you need it. You can do it by hand or using a DI container and conditional/late binding.
http://blog.springsource.com/2007/07/11/setter-injection-versus-constructor-injection-and-the-use-of-required/
We usually advise people to use constructor injection for all
mandatory collaborators and setter injection for all other properties.
I am creating a library that integrates our product with another 3rd party product.
The design being used involves an interface that abstracts the core operations i'd like to integrate to our product, such that when a new 3rd party API is released, we would transparently switch to using it instead of the old one without modifying existing code.
To this end, the actual code that will return a concrete instance of the object interacting with 3rd party API needs to make a decision on to "which implementation to select".
For the simple needs, i assume an entry in the configuration file would suffice to say the fully qualified implementing class name.
Should i use an IoC container in this case, or should i use a Factory Method pattern and code it myself? (use reflection to instantiate the object, etc).
What are the pros and cons for this? Am i missing anything?
Quoting Mark Seemann:
Applications should depend on containers. Frameworks should not.
An IoC container sounds like overkill for your problem. If you have only one dependency to inject, doing it via the config file should be just fine.
Any IoC container is never overkill. You WILL eventually expand on this app if it's successful, or at the least used regularly and you will get requests to add more.
I'm a Castle user, and it's darn easy to add Castle with NuGet then just create a new WindsorContainer() in the startup and register your interfaces and class.
It's like asking if TDD is overkill to make a simple app. You should always (if you can) TDD the app, and use interfaces over concrete in your classes. IoC is too easy to setup now that you're only adding a few lines of code, so why not? it will be much harder later on if you didn't originally use an IoC container and you have intefaces and newed up classes all over your project to organize them all back into an IoC container.
I've been looking at the Common Service Locator as a way of abstracting my IoC container but I've been noticing that some people are strongly against this type of this.
Do people recommend never using it? Always using it? or sometimes using it?
If sometimes, then in what situations would you use it and what situations would you not use it.
Imagine you are writing library code to be used by 3rd party developers. Your code needs to be able to create service objects that these developers provide. However you don’t know which IoC container each of your callers will be using.
The Common Service Locator lets you cope with the above without forcing a given IoC on your users.
Within your library itself you may wish to register your own classes in the IoC, now it gets a lot harder as you need to choose a IoC for your own use that will not get in the way of your callers.
I noticed that one of the arguments against using the CSL is a false one, because developers think this library is only capable of doing the Service Locator pattern. This however isn't the case, because it is easy to use it with the Dependency Injection pattern as well.
However, the CSL library was specially designed for framework designers who need to allows users to register dependencies. Because the library will be calling the CSL directly, from the framework's perspective we're talking about the SL pattern, hence its name.
As a framework designer however, taking a dependency on the CSL shouldn't be taking lightly. For usability of your framework it is normally much better to have your own DI mechanism. A very common mechanism is to set up dependencies in the configuration file. This pattern is used throughout the whole .NET framework. Almost every dependency can be replaced for another. The .NET provider pattern is built on top of this.
When you, as a framework designer, take a dependency on the CSL, it will be harder for users to use your application. Users will have to configure an IoC container and hook it up to the CSL. However, it is not possible for the framework to validate the configuration as can be done while using the .NET configuration system, which as all kind of validation support in it.
I've done some reading on the service locator concept lately. It is a way of helping to reduce coupling, but requires code coupling to the locator - not the container backing the locator, but the locator itself. It is a tradeoff, but can be beneficial in the right situation.
One situation where it can be helpful is when you have code that does not make use of DI, such as legacy code - I am in this boat now. Pulling in required objects via SL, rather than directly creating them, allows the addition of some abstraction. I see it as an intermediate step between SL and DI/IoC.
If you have library code that is in need of services and this code could be hosted in the context of a larger framework/runtime then the framework / runtime would need to provide a mechanism where you can run some custom code on startup wherein you can initialize your container and register dependencies.
A good example of where CSL can be problematic is when using it in the context of MSCRM. You can have custom business logic executed by registering plugins which the MSCRM framework executes on certain events. The problem you run into is where do you run the registration logic since there is no "startup" event that you can subscribe to for setting up your DI container. Even if you could somehow setup your DI you would need to put the CSL and the DI libraries in the GAC since that is the only way to call out to 3rd party code from a plugin (one more item to add to your deployment checklist).
In scenarios such as this you are better off having your dependencies as constructor parameters that the calling code can initialize as it sees fit( via either constructor injection or manually "newing" up the appropriate interface implementation).