IoC 设计 - 服务内部的参考服务定位器,用于动态委托服务

本文关键字:服务 用于 动态 定位器 参考 设计 内部 IoC | 更新日期: 2023-09-27 18:34:47

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

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

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

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

但是,尽管我是 IoC 和 Unity 的新手,但据我所知,从服务中引用静态服务定位器是不好的,所有依赖项都应在构造函数中传递 - 所以我将不胜感激关于可以做到这一点的其他方式的想法,或者在这种情况下是否可以引用服务定位器?

谢谢

克里斯

代码如下:

使用 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());
    }
}

克朗作业类

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();
    }
}

IoC 设计 - 服务内部的参考服务定位器,用于动态委托服务

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

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