Using Autofac as a service locator

前端 未结 3 1979
名媛妹妹
名媛妹妹 2021-01-07 22:34

I\'m using Autofac to handle dependency injection in my application. However, I have one component that does some reflection magic at runtime and I don\'t know at compile-ti

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-07 23:11

    Yes, you can. Just take a dependency on the IComponentContext:

    public class MyComponent
    {
        IComponentContext _context;
        public MyComponent(IComponentContext context)
        {
            _context = context;
        }
    
        public void DoStuff()
        {
            var service = _context.Resolve(...);
        }
    }
    

    Update from the comments: the IComponentContext injected into MyComponent depends on the scope from which MyComponent was resolved. It is thus important to consider with what lifetime scope MyComponent is registered. E.g. using InstancePerLifetimeScope, the context will always resolve to the same scope in which the service depending on MyComponent lives.

提交回复
热议问题