Named bulk registration with windsor castle - dependency-injection

In my project I have the interface IProcess and a lot of classes implementing this interface. I need to register all those implementations. The following code is working fine for me:
Container.Register(Component.For<IProcess>().Named("SampleProcess").ImplementedBy<SampleProcess>());
Container.Register(Component.For<IProcess>().Named("SampleProcess2").ImplementedBy<SampleProcess2>());
However using this approach for registering is tedious if I have a lot of implementations. Therefore I am looking for a registration method to register all implementations of IProcess in a given assembly by name. The name that should be used for the registration key is just the class name.
Can someone pls give me a hint where to look for?

Sounds like a classic scenario for the convention registration API.
container.Register(
Classes.FromThisAssembly()
.BasedOn<IProcess>()
.WithServiceBase()
// and then if you *really* need to explicitly control naming
.Configure(c => c.Named(c.Implementation.Name)
)
Generally explicitly naming your components shouldn't be used, unless you have multiple components with the same implementation class, so just make sure you really need it.

Related

Dependency injection - trying to avoid using a service locator

Following the guidelines I read in:
https://www.devtrends.co.uk/blog/how-not-to-do-dependency-injection-the-static-or-singleton-container
I want to try and avoid using a service locator.
But on the other hand, I don't register all the types in the startup.cs file. I don't think this is right that all these internal types are referenced in the main startup.cs
I currently have a factory class that has a collection of builder classes.
Each builder class is in charge of creating a specific object.
I don't want to create all these builder classes in advance as I might not need to use them and creating them is a bit heavy.
I saw an example of how to achieve this in the link above. However the startup.cs class needs to know all these builders. I don't think this is appropriate, I'd rather have the factory class be the only one that is exposed to them. I was trying to understand if there is some kind of func/action method that I can inject from the startup.cs file into my factory class. This func/action will be in charge of creating/registering the builders and then I can activate this func/action within the class factory. I'd like this func/action to receive the interface/class/maybe name of the builder but using generics isn't working. I searched a lot and didn't find any solution so I assume this is not possible.
Seems I have 2 options:
1. Use service locator. This way only the factory class will know the builders. However if in the future, if I want to change the DI I need to "touch" the factory class (I'm contaminating the factory class). Wanted all the DI code to be located only in the startup.cs class.
2. Register the builders in the startup.cs but now the startup.cs is aware of the builders. This kinda couples the code, not really single role of responsibility
It would have been great to inject the factory class a func/action from the startup.cs that would do the registration but the factory class itself activates it.
Is this possible?
I want to try and avoid using a service locator
Great, because the Service Locator is an anti-patttern.
don't register all the types in the startup.cs file.
You should do your registrations in one single 'area' of your application: the start-up path. This area is commonly referred to as the Composition Root (the place where object graphs are composed).
I don't think this is right that all these internal types are referenced in the main startup.cs
No matter how you design it, the startup assembly is the most volatile part of the system and it always depends on all other assemblies in the application. Either directly or transitively (through another referenced assembly). The whole idea of Dependency Injection is to minimize the coupling between components and the way to do this is to centralize coupling by moving it to the Composition Root. By making types internal however, you are decentralizing object composition and that limits your flexability. For instance, it becomes harder to apply decorators or interceptors for those registered types and control them globally. Read this question and its two top voted answers for more information.
I don't register all the types
The concern of having a Composition Root that is too big is not a valid one. One could easily split out the Composition Root into multiple smaller functions or classes that all reside in the startup assembly. On top of that, if you read this, you'll understand that registering all types explicitly (a.k.a. "Explicit Register") is typically pointless. In that case you're probably better off in using DI without a Container (a.k.a. Pure DI). Composition Roots where all types are registered explicitly are not very maintainable. One of the areas a DI Container becomes powerful is through its batch-registration facilities. They use reflection to load and register a complete set of types in a few lines of code. The addition of new types won't cause your Composition Root to change giving you the highest amount of maintainability.
I don't want to create all these builder classes in advance as I might not need to use them and creating them is a bit heavy
Creation of instances should never be heavy. Your injection constructors should be simple and composing object graphs should be reliable. This makes building even the biggest object graphs extremely fast. Factories should be reduced to an absolute minimum.
TLDR;
Register or compose your object graphs solely in the Composition Root.
Refrain from using the Service Locator anti-pattern; Whole applications can (and should) be built purely with Constructor Injection.
Make injection constructors simple and prevent them from doing anything else than storing their incoming dependencies.
Refrain from using factories to compose services, they are not needed in most cases.

Mock MembershipProvider with custom methods

I have an ASP.NET MVC app that I'm working on. I'm using a custom MembershipProvider (MyCustomMembershipProvider) to access membership information because we already have a database with our own schema that I need to use.
I am using classes similar to the NerdDinner 2 example where I have an AccountMembershipService (implementing an IMembershipService) that contains a MembershipProvider so I can inject a different mock provider. However, I have extended the MyCustomMembershipProvider with a few different methods for CreateUser and ChangePassword. These methods are not available in the MembershipProvider unless you know it's a custom one.
Am I going about this incorrectly? Do I need another layer that is an interface that includes my new provider methods?
I'm not fully sure I understand what your problem is. If you're using a wrapper interface over the MembershipProvider, then it shouldn't matter what methods the provider implements because your app is only using the interface, and you can change the interface to whatever you want.
Or are you asking how you would call your custom methods from your Custom provider? If so, then the whole bit about mocking and what not are just red herrings, because it has nothing to do with the problem.
If that is indeed your problem, then you would simply cast the Membership.Provider method to the type of your provider. Something like this:
var myProvider = Membership.Provider as MyCustomerMembershipProvider;
myProvider.CreateUser(...);

When was the default AccountController sample changed?

I asked this question over on the asp.net forums, and nobody seems to know what i'm talking about. I'm not sure why that is, but I figured I'll ask here to see if there is anyone with some insight.
Back when MVC2 was released, it included a sample AccountController that wrapped the built-in Membership and FormsAuthentication classes with testable interfaces and services. I read a lot about this, and it was considered a good thing because the Membership and FormsAuthentication classes were not easily testable.
Recently, I generated a new sample project with my up to date (SP1, MVC3, Tools Update, etc..) environment and I find that the AccountController is now much simpler. Gone are the Interfaces and MembershipService and FormsAuthenticationServices. The sample now calls the Membership and FormsAuthentication classes directly.
I'm wondering if anyone knows when this happened and why? Are the testable interfaces no longer considered correct? Was there a technical reason to change this?
The best I can figure is that this happened as a part of the change to remove a possible vulnerability when passing return url's on the open url.
Any insight?
The new model resembles EF's code first approach where the AccountModel is a POCO class. Inside the new API there are no longer abstractions but direct calls to static methods such as FormsAuthentication.SetAuthCookie making this code difficult to unit test. Not something I would recommend basing your real world application code upon.
And, yes, they have fixed a vulnerability inside the LogOn method which was not verifying if the return url is a relative url before redirecting.
Personally I would recommend you using abstractions in order to weaken the coupling between your controller logic and its dependencies. This will make the code easier to unit test.
For me passing all those domain models to views without using view models are total anti-patterns and I have never bothered with them. I simply create an empty project and do the things my way. I mean in the default project they even use ViewBag for Christ sake!
The Account Controller was changed with the MVC3 tools update (When they also included the use of jQuery via Nuget)

Using a ServiceLocator in Class LIbraries and MVC DependencyResolver

I've really gotten into the DI/IoC things - it makes some things a lot easier. However, I have a few inherited classes that implement a class with a required parameterless constructor, I thus use a service locator to get what I want:
MyMembershipProivder() : MyMembershipProvider(ServiceLocator.Current.GetInstance<...>){}
MyMembershipProivder(IMemberRepo memberRepo){...}
Works perfect. However, since I'm also using MVC3 DependencyResolver I find myself no other way but to do:
var locator = new NinjectServiceLocator(kernel);
DependencyResolver.SetResolver(locator);
ServiceLocator.SetLocatorProvider(() => locator);
DependencyResolver gets used within the MVC app and the ServiceLocator gets used throughout the various class libraries.
Is this the ideal way to do this? Am I missing something?
Update
In the example above, the class is a custom asp.net mebership provider. The asp.net membership provider factory requires for my custom provider to have a parameterless constructor, forcing me to use the service locator to inject the repository that it uses internally.
You don't need the parameterless constructor, the Dependency Resolver will inject your dependency into the constructor:
MyMembershipProivder(IMemberRepo memberRepo){...}
You can replace the default controller factory (to use parameterless constructors in your controllers):
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
You wont need to replace the default controller factory, see Linkgoron's comment below.
Anyway using the Dependency Resolver for your MVC application and the Service Locator for your class libraries is fine, I think.
Hope this helps.
It seems as if you don't really have a choice, unless you can refactor your application to use DI from the start. So, I guess using custom a Service Locator is your best bet.
Although, if the classes you've "inherited" are the controller classes you can just remove the default constructors and be done with it, as MVC will handle everything for you.
I've never seen the ServiceLocator class, is it this?
EDIT:
As I've said, I don't see that you have any other option for decoupling. Service location is probably your best bet, without introducing too much bloat and complexity.
Stuff that's implemented as something built into the .Net FW you should look for specific solutions like the one presented for the Membership Provider.

StrcutureMap Wiring - Sanity Check Please

Im new to IOC and StructureMap and have an n-level application and am looking at how to setup the wirings (ForRequestedType ...) and just want to check with people with more experience that this is the best way of doing it!
I dont want my UI application object to reference my persistence layer directly so am not able to wire everything up in this UI project.
I now have it working by defining a Registry class in each project which wires up the types in the project as needed. The layer above registers its types and also calls the assembly below and looks for registries so that all types are registered throught the hierrachy.
E.g. I have UI, Service, Domain, and Persistence libraries. In my service layer the registry looks like
Scan(x =>
{
x.Assembly("MyPersistenceProject");
x.LookForRegistries();
});
ForRequestedType<IService>().TheDefault.Is.OfConcreteType<MyService>();
Is this a recommended way of doing this in a setup such as this? Are there better ways and what are the advantages / disadvantages of these approaches in this case?
This sounds good.
If you use default conventions, like having a default implementation OrderSevice for the interface IOrderService you can reduce the wiring by using conventions in StructureMap. The WithDefaultConventions is a method in the Registry to use default conventions. You can also specify your own convention and register it in the registry using the method With, see the StructureMap documentation

Resources