IoC Design - 从服务内部引用服务定位器,用于动态委托服务

时间:2012-05-20 08:48:27

标签: c# .net inversion-of-control ioc-container

我正在使用IoC容器(Unity)来注册接口并解析/实例化对象。

它工作正常,所有依赖于接口的类都被注入到构造函数中,但是我遇到了设计问题。

我有一个CronJob服务,它在特定时间调用注册的委托,它也由服务定位器实例化。

由于可以注册作业,我从实例化的类中引用服务定位器Unity容器,我这样做是因为我不知道在编译时将哪些对象传递给构造函数,因为作业可以动态注册。

然而,虽然我是IoC和团结的新手,但据我所知,从服务中引用静态服务定位器是不好的,所有依赖项都应该在构造函数中传递 - 所以我会很感激其他方式的想法完成或在这种情况下引用服务定位器是否可以?

谢谢,

克里斯

代码如下:

使用Unity的服务定位器

// ServiceManager provides service location facilities, logging facilities, and database access via IUnitOfWork interface
public class ServiceManager
{
    private static readonly UnityContainer m_ServicesContainer = new UnityContainer();
    private static readonly ServiceManager m_Manager = new ServiceManager();
    public static ServiceManager Instance { get { return m_Manager; } }
    private ILogger Logger { get { return Resolve<ILogger>(); } }

    public T Resolve<T>()
    {
        return m_ServicesContainer.Resolve<T>();
    }

    private ServiceManager()
    {
        // register the unit of work class first!!
        RegisterType<IUnitOfWork, UnitOfWork>();
        // always register the logger (without logging)
        RegisterType<ILogger, NLogForEntityFrameworkLogger>(true);
        // always register the settings manager (without logging)
        RegisterType<ISettingsService, SettingsService>();
        RegisterType<IPluginManagerService, PluginManagerService>(true);
        RegisterType<ICronJobService, CronJobService>(true);
        RegisterType<IReminderGeneratorService, ReminderGeneratorService>();
        RegisterType<IInvoiceService, InvoiceService>();
    }

    public void RegisterType<TFrom, TTo>(bool isSingleton = false)
    {
         if (isSingleton == false)
            m_ServicesContainer.RegisterType(typeof(TFrom), typeof(TTo));
        else
            m_ServicesContainer.RegisterType(typeof(TFrom), typeof(TTo), new ContainerControlledLifetimeManager());

    }
}

CronJob类

public static class CronJobDelegates
{
    public static void SyncRecords(BusinessUnit businessUnit)
    {
        ISynchronisationService syncService = ServiceManager.Instance.Resolve<ISynchronisationService>();
        syncService.Sync(businessUnit);
    }
}

class CronJobService : ServiceBaseWithUnitOfWork, ICronJobService
{
    public CronJobService(IUnitOfWork unitOfWork, ILogger logger, ISettingsService settings)
        : base(unitOfWork, logger)
    {
        m_Settings = settings;
        RegisterCronJob("SyncAccountRecords", CronJobDelegates.SyncRecords,"*1****");
    }

    ISettingsService m_Settings;

    public class RegisteredCronJob
    {
        public RegisteredCronJob(string jobName, EventJobDelegate job)
        {
            JobName = jobName;
            Job = job;
        }

        public string JobName { get; private set; }
        public EventJobDelegate Job { get; private set; }
    }

    static object Lock = new object();

    Dictionary<string, EventJobDelegate> CronJobs = new Dictionary<string, EventJobDelegate>();

    public void RegisterCronJob(string jobName, EventJobDelegate jobCallback, string jobSetting)
    {
        lock(Lock)
        {
            if(CronJobs.ContainsKey(jobName))
            {
                LogMessage("Job '" + jobName + "' already registered", LogLevel.Warn);
                // warning job already registered
            }
            else
            {
                CronJob cronJobRecord = UnitOfWork.CronJobRepository.GetByID(jobName);

                if (cronJobRecord == null)
                {
                    CronJob newCronJob = new CronJob()
                    {
                        JobName = jobName,
                        JobSetting = jobSetting
                    };
                    UnitOfWork.CronJobRepository.Insert(newCronJob);
                }
                else
                    jobSetting = cronJobRecord.JobSetting;

                LogMessage("Job '" + jobName + "' registered using settings: " + jobSetting + ". Next run due on UTC " + NCrontab.CrontabSchedule.Parse(jobSetting).GetNextOccurrence(DateTime.UtcNow), LogLevel.Info);

                CronJobs.Add(jobName, jobCallback);
                UnitOfWork.Save();
            }
        }
    }

    public void ProcessEvents()
    {
        foreach(BusinessUnit businessUnit in UnitOfWork.BusinessUnitRepository.Get())
        {
            foreach (CronJob cronJob in UnitOfWork.CronJobRepository.Get())
            {
                lock(Lock)
                {
                    NCrontab.CrontabSchedule schedule = NCrontab.CrontabSchedule.Parse(cronJob.JobSetting);

                    if (schedule.GetNextOccurrence(cronJob.LastRan) > DateTime.UtcNow.AddHours(businessUnit.GmtOffset))
                    {
                        EventJobDelegate jobDelegate;
                        if (CronJobs.TryGetValue(cronJob.JobName, out jobDelegate) == true )
                        {
                            jobDelegate(businessUnit);
                            cronJob.LastRan = DateTime.UtcNow;
                            UnitOfWork.CronJobRepository.Update(cronJob);
                            LogMessage("Job '" + cronJob.JobName + "' ran, next schedule on " + schedule.GetNextOccurrence(cronJob.LastRan));
                        }
                    }
                }
            }
        }
        UnitOfWork.Save();
    }
}

1 个答案:

答案 0 :(得分:1)

您可以注入一个工厂,然后解析调用容器的ISynchronisationService实例,就像在SyncRecords中一样。

有关实施工厂方法的示例,请参阅here,其中列出了几种替代方法。