Search code examples
c#dependency-injectionlight-inject

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?


Solution

  • 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);
        }
    }