问题
I'm writing a small framework that executed a couple of tasks. Some om the tasks needs specific properties which are injected through Ninject.
Let's say that I have the following constructor in my base class that represents a single Task:
protected DDPSchedulerTask(ILogger logger, List<string> platforms, IBackOfficeDataStore backOfficeDataStore, ICommonDataStore commonDataStore)
{
_logger = logger;
_platforms = platforms;
_backOfficeDataStore = backOfficeDataStore;
_commonDataStore = commonDataStore;
}
Those properties are needed for all the tasks, so I inject them using Ninject with the following Ninject module.
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
}
My scheduler object itself if the first entry in the chain which needs to be resolved by Ninject, so I'm resolving this manually through Ninject.
var schedulerInstance = kernel.Get<Scheduler>();
Now, my scheduler have a method which adds tasks to a list, so not by using Ninject:
var tasksList = new List<DDPSchedulerTask>
{
new AWNFileGeneratorTask(_logger, availablePlatforms, _backOfficeDataStore, _commonDataStore)
};
Then, all those tasks are being executed. Now, some of those tasks does require additional dependencies which I would like to resolve through Ninject but how should I do this?
Inside a task, I've created a property with the Inject
attribute, but the object stays nulls.
[Inject]
private IDirectoryResolver directoryResolver { get; set; }
Anyone has an idea on how this can be resolved?
I can pass the kernel around to the different tasks, but something's telling me that this isn't the correct approach.
Kind regards
回答1:
In such cases I usually use a Factory pattern. In the scheduler you can have the task factory as a dependency. This factory can also have multiple methods for creating different types of tasks.
class DDPSchedulerTaskFactory : IDDPSchedulerTaskFactory
{
DDPSchedulerTaskFactory(ILogger logger, List<string> platforms, IBackOfficeDataStore backOfficeDataStore, ICommonDataStore commonDataStore)
{
_logger = logger;
_platforms = platforms;
_backOfficeDataStore = backOfficeDataStore;
_commonDataStore = commonDataStore;
}
public IDDPSchedulerTask CreateNormal(){
return new DDPSchedulerTask(
_logger,
_platforms,
_backOfficeDataStore,
_commonDataStore);
}
public IDDPSchedulerTask CreateSpecial(someAdditionalParameter){
return new AnotherDDPSchedulerTask(
_logger,
_platforms,
_backOfficeDataStore,
_commonDataStore,
someAdditionalParameter);
}
public IDDPSchedulerTask CreateTaskWithDifferentDependenties(yetAnotherParameter){
return new AnotherDDPSchedulerTask(
_logger,
_platforms,
yetAnotherParameter);
}
}
Than in your scheduler you can add tasks like that:
class Scheduler{
IDDPSchedulerTaskFactory _taskFactory;
public Scheduler(IDDPSchedulerTaskFactory taskFactory){
_taskFactory = taskFactory; // factory gets all the needed dependencies for all tasks from DI
}
...
public void ConfigureTasks(){
_tasks.Add(_taskFactory.CreateNormal());
_tasks.Add(_taskFactory.CreateSpecial("Some important message"));
_tasks.Add(_taskFactory.CreateTaskWithDifferentDependenties(123));
}
}
回答2:
You should take advantage of Ninject.Extensions.Factory.
Just create an interface that represents your tasks factory. Then pass information to Ninject that is a factory And he would create for you full implementations of this interface.
using System;
using System.Collections.Generic;
using Ninject;
using Ninject.Extensions.Factory;
internal class Program
{
public static void Main(string[] args)
{
IKernel ninjectKernel = new StandardKernel();
ninjectKernel.Bind<DDPSchedulerTask>().ToSelf();
ninjectKernel.Bind<AWNFileGeneratorTask>().ToSelf();
ninjectKernel.Bind<IDirectoryResolver>().To<DirectoryResolver>();
ninjectKernel.Bind<ITaskFactory>().ToFactory();
var mainTask = ninjectKernel.Get<DDPSchedulerTask>();
mainTask.CreateDbSchedulerTask();
mainTask.CreateAwnFileTask();
Console.ReadLine();
}
}
public interface ITaskFactory
{
TTask CreateTask<TTask>() where TTask : DDPSchedulerTask;
}
public class DDPSchedulerTask
{
private readonly ITaskFactory _tasksFactory;
private readonly List<DDPSchedulerTask> _tasksList;
public DDPSchedulerTask(ITaskFactory tasksFactory)
{
_tasksFactory = tasksFactory;
_tasksList = new List<DDPSchedulerTask>();
}
public void CreateAwnFileTask()
{
var task = _tasksFactory.CreateTask<AWNFileGeneratorTask>();
_tasksList.Add(task);
}
public void CreateDbSchedulerTask()
{
var task = _tasksFactory.CreateTask<DDPSchedulerTask>();
_tasksList.Add(task);
}
}
public class AWNFileGeneratorTask : DDPSchedulerTask
{
[Inject]
public IDirectoryResolver DirectoryResolver { get; set; }
public AWNFileGeneratorTask(ITaskFactory tasksFactory)
: base(tasksFactory)
{
}
}
public interface IDirectoryResolver
{
}
public class DirectoryResolver : IDirectoryResolver
{
}
@gisek As noted Giseke dependency injection via property is not the best solution. You can also use a constructor injection in this example.
public class AWNFileGeneratorTask : DDPSchedulerTask
{
private IDirectoryResolver _directoryResolver;
public AWNFileGeneratorTask(ITaskFactory tasksFactory, IDirectoryResolver directoryResolver)
: base(tasksFactory)
{
_directoryResolver = directoryResolver;
}
}
Extra params injection:
public interface ITaskFactory
{
DDPSchedulerTask CreateDDPSchedulerTask();
AWNFileGeneratorTask CreateAWNFileGeneratorTask(string extraParam);
}
public class AWNFileGeneratorTask : DDPSchedulerTask
{
private IDirectoryResolver _directoryResolver;
private string _extraParam;
public AWNFileGeneratorTask(ITaskFactory tasksFactory, IDirectoryResolver directoryResolver,
string extraParam)
: base(tasksFactory)
{
_extraParam = extraParam;
_directoryResolver = directoryResolver;
}
}
public void CreateAwnFileTask()
{
var task = _tasksFactory.CreateAWNFileGeneratorTask("extra");
_tasksList.Add(task);
}
来源:https://stackoverflow.com/questions/30527596/is-it-a-good-practice-to-pass-the-ninject-kernel-around