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