在ContainerBuilder上,我可以执行以下操作:
builder.Register<ScenariosConfig>(c =>
(ScenariosConfig)c.Resolve<ConfigFactory>()
.Create(typeof(ScenariosConfig)))
.SingleInstance();通过程序集扫描,我可以完成以下操作:
builder.RegisterAssemblyTypes(assemblies)
.Where(HasSingletonAttribute)
.As(t => GetNameMatchingInterfaces(t))
.SingleInstance();现在,问题:有什么方法可以实现以下目标:?
builder.RegisterAssemblyTypes(assemblies)
.Where(... some condition)
.CreateByDelegate((container, type)
=> c.Resolve<ConfigFactory>().Create(type))
.SingleInstance();我已经发现了IRegistrationSource,我可以用它实现类似的目标。然而,我对为我的每一项公约创建大量的IRegistrationSource的性能影响有点怀疑,因为这些约定需要一个代表来创建.还有一个事实是,每当您需要解决应该受这样一个“约定”约束的所有IFoo实例时,都不能使用IRegistrationSource。
发布于 2015-04-24 05:21:03
最后,我们确实选择了使用IRegistrationSource。我“找到”的唯一选择是检测每个反射的所有类型(而不是使用autofac API.)然后为每个用户生成一个委托,并使用autofac注册它。不会产生容易理解的代码..。
因此,为了完整起见,下面是IRegistrationSource实现:
public class ConfigConventionRegistrationSource : IRegistrationSource
{
public IEnumerable<IComponentRegistration> RegistrationsFor(
Service service,
Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
var s = service as IServiceWithType;
if (s != null
&& s.ServiceType.IsClass
&& s.ServiceType.Name.EndsWith("Config")
&& !s.ServiceType.GetInterfaces().Any())
{
yield return RegistrationBuilder
.ForDelegate((componentContext, parameters) =>
CreateConfigByFactory(componentContext, s.ServiceType))
.As(s.ServiceType)
.SingleInstance()
.CreateRegistration();
}
}
private static object CreateConfigByFactory(
IComponentContext componentContext,
Type configType)
{
IConfig configFactory = componentContext.Resolve<IConfig>();
MethodInfo method = Reflector<IConfig>
.GetMethod(x => x.Load<object>())
.GetGenericMethodDefinition()
.MakeGenericMethod(configType);
try
{
return method.Invoke(configFactory, new object[0]);
}
catch (TargetInvocationException tex)
{
ExceptionDispatchInfo
.Capture(tex.InnerException)
.Throw();
throw; // will not be reached as thrown above ;-)
}
}
public bool IsAdapterForIndividualComponents
{
get { return false; }
}
}https://stackoverflow.com/questions/27183751
复制相似问题