Where is the simple equivalent of a StructureMap ObjectFactory injector

I am in the process of migrating from StructureMap to Simple Injector in an ASP.NET MVC3 application.

I am using the MVC3 extension for the DI controller, but I am having trouble trying to replace the static aspects of StructureMap. We have calls for

StructureMap.ObjectFactory.GetInstance<Interface>() 

at different levels of the application. This is not like Simple Injector has a way to do this.

Am I missing something? Or is a simple injector not applicable for my application?

Please advise in advance and in advance.

+7
source share
1 answer

Giving applications direct access to the container is considered bad practice. This is the form of a service locator pattern that is considered an anti-pattern :

In short, the problem with the Service Locator is that it hides the dependency class, causing runtime errors instead of compile-time errors, and also make the code more difficult to maintain, as it becomes unclear when you introduce the violation.

Since this is considered bad, Simple Injector does not contain anything like StructureMap ObjectFactory.GetInstance . And, in fact, the author of StructureMap considers removing the ObjectFactory API in the release of the StructureMap structure.

However, nothing prevents you from storing an instance of SimpleInjector.Container in a static field and using this application:

 // Service Locator implementation in low application layer. public static class ObjectFactory { private static SimpleInjector.Container container; public static void SetContainer(Container container) { ObjectFactory.container = container; } public static void GetInstance<T>() where T : class { return container.GetInstance<T>(); } } 

At the root of the composition:

 public static void Initialize() { var container = new Container(); InitializeContainer(container); DependencyResolver.SetResolver( new SimpleInjectorDependencyResolver(container)); // Set the service locator here ObjectFactory.SetContainer(container); } 

Thus, there are no restrictions in Simple Injector that prevent you from doing this, but frankly, you are already witnessing one of the reasons why the Service Locator is bad: you switched containers, and now you need to change the application code.

Perhaps at the moment it is easiest to save the container in a static field (as shown in the example above), but please take the time to understand why this template is bad and reorganize this template depending on the dependencies of the injection (and especially the constructor injection) .

Good luck.

+14
source

All Articles