简体   繁体   中英

How to inject IServiceContainer when using LighInject?

I am using LightInject and now I need to know how to resolve a type myself. I've tried to use IServiceContainer , but when I inject this interface into my class I get an error saying that is an unresolved dependency.

The thing I want te solve is this. At runtime I have a Type that I need a instance from. So I want to do something like SomeResolver.GetInstance(myType) .

How can I do this with LightInject?

I've got a working solution. Don't know if this is the 'preferred' way, so if anyone has a better idea, please let me know:)

Here's what I use now:

container.Register<ITypeResolver>(s => new LightInjectTypeResolver(s));

And here's the class implementing ITypeResolver :

public class LightInjectTypeResolver : ITypeResolver
{
    private readonly IServiceFactory _serviceFactory;

    public LightInjectTypeResolver(IServiceFactory serviceFactory)
    {
        _serviceFactory = serviceFactory;
    }

    public object GetType(Type entity)
    {
        return _serviceFactory.GetInstance(entity);
    }
}

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