简体   繁体   中英

How do I access the same IoC container (i.e. Unity) in multiple classes?

How do I access the same IoC container (ie Unity) in multiple classes?

The following container is a local variable when embedded inside a method. As a result, How do I access this container in other classes?

    using (var container = new UnityContainer())
    {
        container.RegisterInstance(typeof(IDraftRepository), new MockDraftRepository());
    }

You can create a static class and make it expose the container as a property. Then all the other classes can access and use it. Another way is to inject IUnityContainer into the classes that want to use it (via constructor injection).

Having said that, I strongly recommend that you don't do this. The only place where the container should be used is the Composition Root which is where you compose all of your classes together in the entry point of the application.

And if your classes need dependencies, you can inject them in the constructor.

Using the container in your classes is called Service Location and is considered an anti-pattern .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM