如何使用Ninject

时间:2016-08-24 12:42:47

标签: c# asp.net asp.net-mvc dependency-injection ninject

在我的MVC应用程序中,我有一个“预定工作”的概念。

作业继承自接口,然后(通过反射)在应用程序启动时自动注册。

现在,在我的应用程序中,我正在使用Ninject for DI来帮助我的控制器更加可单元测试。我也很乐意将ninject用于我的预定工作,但我现在正在使用“穷人的DI”来实例化我的Job与他们的依赖关系。

那么,我究竟会如何使用Ninject而不是穷人的DI?

工作界面:

public interface IScheduledJob
{
    /// <summary>
    /// Use Cron method to return frequency expression
    /// </summary>
    string Frequency { get; }

    /// <summary>
    /// The entry point of the Job
    /// </summary>
    void DoWork();
}

工作初始代码:

private void ConfigureSchedules(IAppBuilder app)
    {
        // Get all types that implement the scheduler interface
        IEnumerable<Type> jobs = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(p => typeof(IScheduledJob).IsAssignableFrom(p) && !p.IsInterface);
        foreach (var jobType in jobs)
        {
            // Create instance of job
            IScheduledJob job = (IScheduledJob)Activator.CreateInstance(jobType);
            // Add to schedule
            RecurringJob.AddOrUpdate(() => job.DoWork(), job.Frequency);
        }
    }

预定工作Ctors:

public class SynchronizerScheduledJob : IScheduledJob
{
    #region Private Members

    private IMagentoSoapService _magentoSoapService;
    private IMagentoSoapCredentialProvider _credsProvider;
    private IUnitOfWork _unitOfWork;
    private IOrderHubService _orderHubService;

    #endregion

    #region Ctors

    public SynchronizerScheduledJob(
       IMagentoSoapService service,
       IMagentoSoapCredentialProvider credsProvider,
       IUnitOfWork unitOfWork,
       IOrderHubService orderHubService)
    {
        _magentoSoapService = service;
        _credsProvider = credsProvider;
        _unitOfWork = unitOfWork;
        _orderHubService = orderHubService;
    }

    /// <summary>
    /// Poor man's DI Ctor
    /// </summary>
    public SynchronizerScheduledJob() : this(
            new MagentoSoapService(),
            new MagentoSoapCredentialProvider(),
            new UnitOfWork(AppDbContext.Create()),
            new OrderHubService())
    { }
}

0 个答案:

没有答案