我在写一个执行几个任务的小框架。 有些任务需要通过Ninject注入的特定属性。传递Ninject内核是否是一个好习惯?
比方说,我在我的基类下面的构造表示单个任务:
protected DDPSchedulerTask(ILogger logger, List<string> platforms, IBackOfficeDataStore backOfficeDataStore, ICommonDataStore commonDataStore)
{
_logger = logger;
_platforms = platforms;
_backOfficeDataStore = backOfficeDataStore;
_commonDataStore = commonDataStore;
}
所需的所有任务,这些属性,所以我使用Ninject用以下Ninject模块注入其中。
public class DDPDependencyInjectionBindingConfiguration : NinjectModule
{
#region NinjectModule Members
/// <summary>
/// Loads the module into the kernel.
/// </summary>
public override void Load()
{
Bind<Scheduler>().ToSelf(); // Make sure that the 'Scheduler' is resolved to itself.
Bind<ILogger>().ToMethod(context => LogFactory.Create()); // Make sure that an instance of an ILogger is created through the LogFactory.
// Straightforward binding.
Bind<ICommonDataStore>().To<Common>();
Bind<IBackOfficeDataStore>().To<BtDbInteract>();
Bind<IDirectoryResolver>().To<Demo>();
}
#endregion
}
我的调度对象本身如果需要由Ninject解决链中的第一个条目,所以我这个手动解决通过Ninject。现在
var schedulerInstance = kernel.Get<Scheduler>();
,我有调度这增加了任务列表的方法,所以无法使用Ninject:
var tasksList = new List<DDPSchedulerTask>
{
new AWNFileGeneratorTask(_logger, availablePlatforms, _backOfficeDataStore, _commonDataStore)
};
然后,正在执行所有这些任务。 现在,其中一些任务确实需要额外的依赖关系,我想通过Ninject来解决这些问题,但我应该如何执行此操作?
在任务中,我创建了一个属性Inject
属性,但对象保留空值。
[Inject]
private IDirectoryResolver directoryResolver { get; set; }
任何人都有关于如何解决这个问题的想法?
我可以将内核传递给不同的任务,但有些东西告诉我这不是正确的方法。
亲切的问候
好的事,但在你的代码是不正确的。在你的create方法中,返回类型被设置为“DDPSchedulerTask”,但你要返回一个“DDPSchedulerTaskFactory”。另外,你能否解释一下你的解决方案?我应该从哪里调用create方法,因为我希望Unity的其他属性也可以被注入。 – Complexity
@Complexity是的,只是纠正它 – gisek
感谢您的更正。你介意从我需要调用这个工厂的地方展示我,因为我想继续使用Ninject来确保依赖注入。我没有看到Ninject在这里的胶水。我仍然需要传入'someAdditionalParameters',我想让Ninject内核来解决这个问题。 – Complexity