我使用的是CacheManager,它使用工廠來創建實例。我不想註冊我聲明的每種類型的ICacheManager,所以我正在尋找一種方法來使用動態解析方法註冊泛型類型。使用Ninject,我可以這樣做:通過方法解決的Autofac註冊
kernel
.Bind(typeof(ICacheManager<>))
.ToMethod((context) => CacheFactory.FromConfiguration(context.GenericArguments[0], "defaultCache"))
.InSingletonScope();
其中context.GenericArguments [0]將是我的通用類型。例如,來自
的對象ICacheManager<object> cache;
如何使用Autofac做類似這樣的事情?
編輯
基於以下西里爾的回答工作IRegistrationSource。由於CacheManager使用CacheManager實例ID預先添加密鑰,因此SingleInstance是必需的。
public class CacheManagerRegistrationSource : IRegistrationSource
{
public Boolean IsAdapterForIndividualComponents
{
get
{
return false;
}
}
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
IServiceWithType typedService = service as IServiceWithType;
if (typedService == null || !typedService.ServiceType.IsGenericType)
{
yield break;
}
Type cacheManagerType = typedService.ServiceType;
if (cacheManagerType.GetGenericTypeDefinition() != typeof(ICacheManager<>))
{
yield break;
}
IComponentRegistration registration = (IComponentRegistration)RegistrationBuilder.ForDelegate(cacheManagerType, (c, p) =>
{
return CacheFactory.FromConfiguration(cacheManagerType.GetGenericArguments()[0], "defaultCache");
})
.SingleInstance()
.CreateRegistration();
yield return registration;
}
}
謝謝。你的答案几乎是現貨。我已經在我的問題中發佈了工作代碼。 –