我使用的是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;
}
}
谢谢。你的答案几乎是现货。我已经在我的问题中发布了工作代码。 –