讓我們想象一下,你有這幾種:
public class Thing1 { }
public class Thing2 { }
public class Thing3 { }
public interface IUploadStrategy<T1, T2> { }
public class UploadStrategy1<T> : IUploadStrategy<Thing1, T> { }
public class UploadStrategy2<T> : IUploadStrategy<Thing2, T> { }
當你解決IUploadStrategy<Thing1, String>
你想Autofac返回的UploadStrategy1<String>
一個實例,當你解決IUploadStrategy<Thing2, String>
你想要的UploadStrategy2<String>
實例
你可以這樣註冊這些類型:
builder.RegisterGeneric(typeof(UploadStrategy1<>)).As(typeof(IUploadStrategy<,>));
builder.RegisterGeneric(typeof(UploadStrategy2<>)).As(typeof(IUploadStrategy<,>));
通過這樣做Autofac將自動考慮對T1
的限制。
所以,
var s1 = container.Resolve<IUploadStrategy<Thing1, String>>();
Console.WriteLine(s1.GetType()); // will be UploadStrategy1
var s2 = container.Resolve<IUploadStrategy<Thing2, String>>();
Console.WriteLine(s2.GetType()); // will be UploadStrategy2
會按預期工作。請參閱此dotnetfiddle以獲得實況樣本:https://dotnetfiddle.net/cwvait
如果要自動解析這些類型,可以考慮使用RegisterAssemblyTypes
方法。不幸的是,這種方法不會讓你做你想做的事,因爲它不是一個RegisterAssemblyGenericTypes
方法。你將不得不掃描自己的裝配。例如:
foreach (Type t in typeof(Program).Assembly
.GetLoadableTypes()
.Where(t => t.GetInterfaces()
.Any(i => i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(IUploadStrategy<,>))))
{
builder.RegisterGeneric(t).As(typeof(IUploadStrategy<,>));
}
的GetLoadableTypes
方法是位於Autofac.Util
命名空間擴展方法,這是內部使用RegisterAssemblyTypes
方法的方法。
當你解決'IUploadStrategy'你想'UploadStrategy1 '當你解決'IUploadStrategy '你想'UploadStrategy2 '? (工作示例:https://dotnetfiddle.net/cwvait) –
使用簡單注入器,您可以簡單地調用'container.RegisterOpenGeneric(typeof(IUploadStrategy <,>),typeof(UploadStrategy1 <>));',但我不確定if Autofac支持這種情況。 – Steven
@CyrilDurand這部分讓我在那裏,試圖讓我可以註冊'儘可能多',而不是單獨。我想我會需要一個基類。 – Seth