[英]Generic type constraint constructor limitation, need advice
I'm trying to instantiate an object in the constructor of a class based on what type parameter was passed to create the instance of said class. 我试图基于传递了什么类型参数来创建所述类的实例的实例化类的构造函数中的对象。
public class DefaultController<TEntity, TStrategy> : ApiController, IDisposable where TEntity : class, IEntity where TStrategy: BaseStrategy<TEntity>
{
public IStrategy<TEntity> strategy { get; set; }
public DefaultController()
{
//strategy = ??
}
}
And here's BaseStrategy
这是
BaseStrategy
public abstract class BaseStrategy<TEntity> : IStrategy<TEntity> where TEntity : class, IEntity
{
private IRepository<TEntity> repository;
public BaseStrategy(IRepository<TEntity> _repository)
{
repository = _repository;
}
//implements a bunch of methods...
}
As you can see, BaseStategy
has no parameter-less constructor which makes it impossible to use the new()
generic constraint in DefaultController
如您所见,
BaseStategy
没有无参数构造函数,这使得无法在DefaultController
使用new()
泛型约束。
What I'm trying to achieve is, from a class extending DefaultController
, configure which strategy to use 我想要实现的是,从扩展
DefaultController
的类中,配置要使用的策略
public class UserController : DefaultController<User, GreatStrategy<User>>
{
// GreatStrategy extends BaseStrategy
}
Any workaround to make the magic work or another approach perhaps ? 是否有任何变通办法可以使魔术发挥作用,或者采取其他方法?
Thanks. 谢谢。
Is there a reason DefaultController needs a parameterless constructor? 是否有理由DefaultController需要无参数构造函数? You could try:
您可以尝试:
public DefaultController(IStrategy<IEntity> strategy) : base(strategy)
{
// Do stuff
}
And then in your UserController constructor: 然后在您的UserController构造函数中:
public UserController() : base(new GreatStrategy<User>()) {
// Do stuff
}
Are you using IoC in your application? 您在应用程序中使用IoC吗? If so, you can register your strategies and inject them into the controller constructors so that you don't have to spin up a new Strategy in the base constructor call.
如果是这样,您可以注册策略并将其注入到控制器构造函数中,这样就不必在基础构造函数调用中启动新的Strategy了。
Hope this gives you some guidance moving forward. 希望这能为您提供一些指导。
I ended up modifying the constructors of the default controller and of all controllers extending it as such: 我最终修改了默认控制器的构造函数以及所有扩展它的控制器,如下所示:
public DefaultController(IStrategy<TEntity> _strategy)
{
strategy = _strategy; // 'strategy' is a local member implementing IStrategy...
}
And a controller extending default controller has a constructor like: 扩展默认控制器的控制器具有如下构造函数:
public class UserController : DefaultController<User>
{
public UserController()
: base (new GreatStrategy<User>(new Repository<User>()))
{
//GreatStrategy extends BaseStrategy...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.