1

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?

Martijn
  • 24,441
  • 60
  • 174
  • 261
  • 1
    Make sure you're not abusing the container as [Service Locator](https://freecontent.manning.com/the-service-locator-anti-pattern/). – Steven Oct 01 '19 at 20:17
  • @Steven No I'm not. I assembling the query / command type using a Command- or QueryProcessor. When I have the type, I want to get an instance of that type. – Martijn Oct 02 '19 at 06:22
  • @Martijn Can you include some code to provide a better understanding of what it is you are referring to. – Nkosi Oct 02 '19 at 11:21

1 Answers1

1

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);
    }
}
Martijn
  • 24,441
  • 60
  • 174
  • 261
  • Thanks for this @Martijn - I'm in a similar circumstance. What wasn't obvious to me originally was that the overload for container.RegisterType(s => ...) passes in the IServiceFactory in the lambda. Making the move to Autofac and slowly learning :) – Jedidja Aug 08 '20 at 15:53