简体   繁体   中英

How to register generic class with AutoFac that requires parameters?

AutoFac lets you register generic classes with builder.RegisterGeneric(Type type) , however it does not accept parameters for construction. The description of the method even says:

Register an un-parametrized geenric type

However, what if I have a generic interface IService implemented by Service, which requires some parameters?

Currently I have it registered like this:

builder.Register(c =>
    new Service<Class1>(
        parameter1,
        parameter2))
    .As<IService<Class1>>();

In registration I have to specify the exact type of T (Class1 in this case). Can I do it more generically, so that I have one registration working for any T?

Every thing is documented here: https://autofaccn.readthedocs.io/en/latest/register/parameters.html

Basically, you can keep using RegisterGeneric and use the WithParameter

builder.RegisterGeneric(typeof(Service<>))
       .WithParameter("nameOfParam1", parameter1)
       .WithParameter("nameOfParam2", parameter2)
       .As(typeof(IService<>));

And for the ones looking for with multiple Ttypes (like me).

builder.RegisterGeneric(typeof(BaseGeneralCrud<,,>)).As(typeof(IBaseGeneralCrud<,,>)).InstancePerLifetimeScope();

and here is the class definition looks like:

public class BaseGeneralCrud<TEntity, TDto, TIdType> : IBaseGeneralCrud<TEntity,TDto,TIdType> 
        where TEntity : class, IHasIdColumn<TIdType>
        where TDto : IHasIdColumn<TIdType> , new()
        where TIdType : notnull 
{
    private readonly IRepository<TEntity,TIdType> _repository;

    private readonly IMapper _mapper;

    public BaseGeneralCrud(IRepository<TEntity,TIdType> repository, IMapper mapper)
    {
        _repository = repository;
        _mapper = mapper;
    }

    // there are some methods defined here..

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM