Resolving Generic Interface with Autofac

前端 未结 2 1215
难免孤独
难免孤独 2020-12-02 15:48

Given the following code, how do I resolve the right SomeInstance in autofac?

public class BaseClass {}

public class SubClass1 : BaseClass {}

public class          


        
2条回答
  •  伪装坚强ぢ
    2020-12-02 16:02

    Autofac supports open generics. You can use the following code if generics type is known at compile time:

    var builder = new ContainerBuilder();
    
    builder.RegisterGeneric(typeof(SomeInstance1<>))
      .As(typeof(IGenericInterface<>));              
    
    var container = builder.Build();
    
    var instance1 = container.Resolve>();
    
    Assert.IsInstanceOfType(typeof(SomeInstance1), instance1);
    

    If type parameter is not known until runtime (which is likely your case if you want to iterate through collection of types) then you can build your type using MakeGenericType:

            var typeInRuntime = typeof (SubClass1);
            var instance1 = container.Resolve(typeof(IGenericInterface<>).MakeGenericType(typeInRuntime));
    

提交回复
热议问题