简体   繁体   中英

Resolve a service manually in Web API using Autofac

How can I resolve a service manually in a Web API project using Autofac. I have a class called Foo. Foo is instantiated by Activator.CreateInstance by another class that I have no control over, which means it would call the paramaterless constructor.

I have a few properties that need to be injected in the Foo class. Now since the calling class calls the paramaterless constructor, I need to resolve these properties manually.

public class Foo
{

    private IService Instance;

    public Foo()
    {
        //How do I get the per request lifetime scoped dependency resolver here
        IService = (Dependency Resolver).Resolve<IService>();
    }

}

Since you have no control over the construction of this class, then the only way to do this is via a Service Locator.

Although the service locator is considered an anti-pattern , restrictions such as the one that you have force usage for such patterns.

You would have to create a static class called something like ServiceLocator. It should have some methods to register services (or it should wrap the DI container, which is what you want in this case), and other methods to locate services.

Take a look at the Locator class here for a sample locator. In your case however, you simply need a similar class that wraps the AutoFac container. So, create a static method in such Service Locator class to receive and wrap a DI container.

Regarding lifetime, you can create a special method in your service locator that allows you to resolve services using a special lifetime type (by invoking the DI container appropriately).

Having a Service Locator inside your project will create temptation to use it in situations where Dependency Injection should be used instead (which is almost all the time). Make sure that you use the Service Locator only for such cases.

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