使用不同的构造函数为

时间:2017-04-16 03:58:00

标签: c# design-patterns asp.net-core

我有两个不同构造函数的类 有一个参数

 public TagService(IRepositoryAsync<Tag> tagRespository):base(tagRespository)
 {
      _tagRespository = tagRespository;
 }

有两个参数。

 public AdsService(IRepositoryAsync<Ads> iadsRepository,IUnitOfWork unitOfWork):base(iadsRepository)
 {
      this._iadsRepository = iadsRepository;
      this._unitOfWork = unitOfWork;
 }

一开始,我使用下面的方法来初始化课程。

//services have different constractors
Service = (TEntityService)System.Activator.CreateInstance(
   typeof(TEntityService),
   new object[] { _repository, _unitOfWork }
);

但是,它不适用于只有一个参数。对于上述情况有没有更好的方法。我想创建一个方法,允许在构造函数中使用不同的参数创建一个不同的类。

2 个答案:

答案 0 :(得分:1)

听起来你需要一个依赖注入(DI)库,比如AutofacNijectSimple injector

E.g。简单的注射器:

// 1. Create a new Simple Injector container
container = new Container();

// 2. Configure the container (register)
container.Register<IRepositoryAsync<Tag>, TagService>();
container.Register<IRepositoryAsync<Ads>, AdsService>();
container.Register<IUnitOfWork >();

// 3. Verify your configuration
container.Verify();

//4  
var service = container.GetInstance<TEntityService>();

答案 1 :(得分:0)

  

我想创建一个方法,可以在构造函数中创建具有不同参数的不同类。

嗯,我想最简单的方法就是检查每个案例。

public static TEntityService CreateService(object[] constructorParameters) {
    if (constructorParameters.Length == 1 &&
        constructorParameters[0] is IRepositoryAsync<Tag>) {
        return (TEntityService)System.Activator.CreateInstance(typeof(TagService), constructorParameters);
    } else if (constructorParameters.Length == 2 &&
        constructorParameters[0] is IRepositoryAsync<Ads> &&
        constructorParameters[1] is IUnitOfWork) {
        return (TEntityService)System.Activator.CreateInstance(typeof(AdsService), constructorParameters);
    } else {
        return null; // or you can throw an exception
    }
}