Access or get Autofac Container inside a static class

前端 未结 2 1371
北荒
北荒 2021-02-09 17:36

I need to get or access to my IoC container in a static class. This is my (simplified) scenario:

I register dependencies for ASP .net Web Api in a Startup class (but als

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-09 18:34

    You can create a static method inside your DomainEvents class to inject the container like this:

    public static class DomainEvents
    {
        public static void SetContainer(IContainer container)
        {
            Container = container;
        }
    
        ....
    }
    

    And then from your ASP.NET application, call this method to inject the container:

    DomainEvents.SetContainer(container);
    

    Please note that I am giving you a direct answer to your question. However, here are some issues that I see with this:

    • Static classes should not be used when the class requires dependencies. In such case, refactor to use a non-static class and use Constructor Injection to inject the dependencies that you need in the class.
    • Using the container outside of the Composition Root is called Service Location and is considered an anti-pattern.
    • Class libraries should not use the container or even have a Composition Root. Quoting from the Composition Root article that I referenced:

    Only applications should have Composition Roots. Libraries and frameworks shouldn't.

提交回复
热议问题