Reputation: 4020
In my code, currently types are registered with lots of duplicated code, e.g.
builder.RegisterType<UserViewModelValidation>()
.As<IValidator<UserViewModel>>()
.PropertiesAutowired().InstancePerLifetimeScope();
builder.RegisterType<RoleValidation>()
.As<IValidator<Role>>()
.PropertiesAutowired().InstancePerLifetimeScope();
Instead of having to configure each of these registrations one by one, is there a way to configure a group of them?
So in the above code, it's specifically the PropertiesAutowired()
function and InstancePerLifetimeScope()
function which is generic to a group of type registrations.
Upvotes: 0
Views: 24
Reputation: 4020
In addition to Cyril's answer, I created some additional extensions for registering types in my application using 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();
}
Usage examples:
builder.RegisterInstance<UnitOfWork, IUnitOfWork>();
builder.RegisterAutowiredInstance<Authorize>();
builder.RegisterGenericInstance(typeof(EntityBaseRepository<>), typeof(IEntityBaseRepository<>));
Helps to reduce the amount of redundant code and typing when registering new types.
Upvotes: 0
Reputation: 16192
You can create a custom extension method that will do what you want.
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();
}
}
And then register your type like this :
builder.RegisterValidator<UserViewModelValidation, UserViewModel>();
builder.RegisterValidator<RoleValidation, Role>();
Upvotes: 2