Where's Simple Injector's equivalent of StructureMap's ObjectFactory
Asked Answered
A

1

8

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.

Agram answered 23/7, 2012 at 22:0 Comment(0)
Y
15

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).

Yonyona answered 3/8, 2012 at 14:13 Comment(2)
Thanks for the explanation. I have re-factored the code where we are not using the service locator anti-pattern anymore.Agram
in public static void GetInstance<T>() where T : class line, void should be T, Am I correct?Tripodic

© 2022 - 2024 — McMap. All rights reserved.