在我的代码中,当前类型注册了大量重复代码,例如
builder.RegisterType<UserViewModelValidation>()
.As<IValidator<UserViewModel>>()
.PropertiesAutowired().InstancePerLifetimeScope();
builder.RegisterType<RoleValidation>()
.As<IValidator<Role>>()
.PropertiesAutowired().InstancePerLifetimeScope();
有没有办法配置一组注册,而不必逐个配置这些注册?
因此,在上面的代码中,它具体是PropertiesAutowired()
函数和InstancePerLifetimeScope()
函数,它对于一组类型注册是通用的。
答案 0 :(得分:2)
您可以创建一个可以执行所需操作的自定义扩展方法。
public static class RegistrationExtensions
{
public static IRegistrationBuilder<TValidator, ConcreteReflectionActivatorData, SingleRegistrationStyle>
RegisterValidator<TValidator, TViewModel>(this ContainerBuilder builder)
{
return builder.RegisterType<TValidator>()
.As<IValidator<TViewModel>>()
.PropertiesAutowired()
.InstancePerLifetimeScope();
}
}
然后注册您的类型:
builder.RegisterValidator<UserViewModelValidation, UserViewModel>();
builder.RegisterValidator<RoleValidation, Role>();
答案 1 :(得分:0)
除了Cyril的回答,我还使用Autofac为我的应用程序中的类型注册创建了一些额外的扩展。
public static IRegistrationBuilder<T, ConcreteReflectionActivatorData, SingleRegistrationStyle>
RegisterInstance<T, TServiceType>(this ContainerBuilder builder)
{
return builder.RegisterType<T>().As<TServiceType>().InstancePerLifetimeScope();
}
public static IRegistrationBuilder<T, ConcreteReflectionActivatorData, SingleRegistrationStyle>
RegisterAutowiredInstance<T>(this ContainerBuilder builder)
{
return builder.RegisterType<T>().PropertiesAutowired().InstancePerRequest();
}
public static IRegistrationBuilder<object, ReflectionActivatorData, DynamicRegistrationStyle>
RegisterGenericInstance(this ContainerBuilder builder, Type type, Type serviceType)
{
return builder.RegisterGeneric(type).As(serviceType).InstancePerRequest();
}
用法示例:
builder.RegisterInstance<UnitOfWork, IUnitOfWork>();
builder.RegisterAutowiredInstance<Authorize>();
builder.RegisterGenericInstance(typeof(EntityBaseRepository<>), typeof(IEntityBaseRepository<>));
有助于在注册新类型时减少冗余代码和键入的数量。