Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where's Simple Injector's equivalent of StructureMap's ObjectFactory

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

I am using the MVC3 extension for controller DI, but I am running into an issue with trying to replace the static aspects of StructureMap. We have calls to

StructureMap.ObjectFactory.GetInstance<Interface>()

throughout different layers of the app. It does not look like Simple Injector has a way to do that.

Am I missing something? Or is Simple Injector not applicable for my application?

Please advise and thanks in advance.

like image 568
Will Avatar asked Jul 23 '12 22:07

Will


1 Answers

Allowing the application to directly access the container is considered to be bad practice. It is an form of the Service Locator anti-pattern.

Because this is considered to be a bad thing, Simple Injector does not contain anything like StructureMap's ObjectFactory.GetInstance. And as a matter of fact, the author of StructureMap is considering the removal of the ObjectFactory API in a furure release of StructureMap.

However, nothing stops you from storing the SimpleInjector.Container instance in a static field and let the application use this:

// 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 T GetInstance<T>() where T : class
    {
        return container.GetInstance<T>();
    }
}

In Composition root:

public static void Initialize()
{
   var container = new Container();      

   InitializeContainer(container);
   
   DependencyResolver.SetResolver(
        new SimpleInjectorDependencyResolver(container));   

   // Set the service locator here
   ObjectFactory.SetContainer(container);
}

So there is no limitation in the Simple Injector that prevents you from doing this, but frankly, you are already witnessing one of the reasons why Service Locator is a bad thing: you switched containers and now you have to change application code.

Perhaps for now it is easiest for you to save the container in a static field (as shown in the example above), but please take the time to understand why this pattern is bad, and do refactor away from this pattern towards dependency injection (and especially constructor injection).

like image 109
Steven Avatar answered Oct 14 '22 10:10

Steven