Unity IOC和Factory模式以及存储库模式

时间:2012-11-22 19:17:35

标签: c# unity-container enterprise-library factory-pattern

我正在尝试在我正在编写的程序中使用企业库的Unity Block。

但我认为我使用依赖注入错误。我想知道是否有人可以指出我正确的方向。

    static void Main(string[] args)
        {
                using (IUnityContainer container = new UnityContainer())
                {
                    InitialiseContainer(container);
                    DataCopierFactory dcFactory = new DataCopierFactory();

                    ERunOptions dataCopierType = ExtractParams(args);

                    IDataCopier dataCopier = dcFactory.CreateDataCopier((int)dataCopierType, container);
                    dataCopier.DetectChanges();
                    dataCopier.ParseData();
                    dataCopier.CopyData();
                }
            }
         }
 //use the ioc container to register the EF context type to the repository interfaces..
        private static void InitialiseContainer(IUnityContainer container)
        {

            //add Extensions:
            container.AddNewExtension<Interception>();

            //Licence Schedule
            container.RegisterType<IEFContext, LTE_DownFromWeb_EFContext>("DataCopier.ScheduleDataCopier.Source");
            container.RegisterType<IEFContext, LTE_Licensing_EFContext>("DataCopier.ScheduleDataCopier.Destination");

            container.RegisterType<IRepositorySession>("Schedule_Source",new InjectionConstructor(container.Resolve<IEFContext>("DataCopier.ScheduleDataCopier.Source")));
            container.RegisterType<IRepositorySession>("Schedule_Destination",new InjectionConstructor(container.Resolve<IEFContext>("DataCopier.ScheduleDataCopier.Destination")));



        }

基本上,DataCopier Factory创建了一个DataCopier的实例,如下所示:

DataCopierFactory:

 //return a data copier that will transfer data from any DB to any other DB
        public IDataCopier CreateDataCopier(int i, IUnityContainer container)
        {
            switch(i)
            {
                case 1:
                    return new ScheduleDataCopier(container);

                default:
                    throw new InvalidOperationException("Parameter " + i + " does not exist");
            }
        }

数据复印机如下所示:

     class ScheduleDataCopier : IDataCopier
    {
        private List<Site> _sites;
        private List<SitesAndApparatuses> _scheduleList;
        private IUnityContainer _container;
        public ScheduleDataCopier(IUnityContainer container)
        {
            _container = container;
            _scheduleList = new List<SitesAndApparatuses>();
        }

        //check if new sites registration has arrived in tblSites on down from web db.
        public bool DetectChanges()
        {
            using (var db = _container.Resolve<IRepositorySession>("Schedule_Source"))
            { 
                SiteAudit lastSite = new SitesAuditRepository().GetLatest();
                var sitesRepo = new SitesRepository();
                var sites = sitesRepo.Where(x => x.SID > lastSite.SALatestSID);

                if (sites.Count() < 1)
                {
                    return false;
                }
                _sites = sites.ToList();
                db.Dispose();
            }
            return true;
        }
        //parse the data into a list of object SitesAndApparatuses
        public bool ParseData()
        {
            try
            {
                foreach (Site s in _sites)
                {
                    var schedule = (SitesAndApparatuses)XmlObjectBuilder.Deserialize(typeof(SitesAndApparatuses), s.XMLFile);
                    schedule.acCode = s.Registration.RAcCode;
                    _scheduleList.Add(schedule);
                }
            }
            catch (Exception ex)
            {
                throw new NotImplementedException("HANDLE THIS SHIT!", ex);
            }
            return true;
        }

        public bool CopyData()
        {
            try
            {
               using (var db = _container.Resolve<IRepositorySession>("Schedule_Destination"))
                {
                        var licensingScheduleRepo = new LicensingScheduleRepository();
                       //some logic
                    db.Commit();
                }
            }
            catch (Exception ex)
            {
            }
                return true;
        }
}

第二个问题,我在Datacopier类中使用我传递的统一容器解决了我的工作单元对象RepositorySession ...这是错误的方法,为什么,我很难在网上找到任何信息?

对于有人阅读来说,这可能是太多的代码..但我希望得到答案!

提前致谢 尼尔

1 个答案:

答案 0 :(得分:3)

我会做类似的事情:

container.RegisterType<IEFContext, LTE_DownFromWeb_EFContext>("Source");
container.RegisterType<IEFContext, LTE_Licensing_EFContext>("Destination");
container.RegisterType<IRepositorySession>("Source",new InjectionConstructor(new ResolvedParameter<IEFContext>("Source"));
container.RegisterType<IRepositorySession>("Destination",new InjectionConstructor(new ResolvedParameter<IEFContext>("Destination")));
container.RegisterType<IDataCopier,ScheduleDataCopier>("0",new InjectionConstructor(new[] {new ResolvedParameter<IRepositorySession("Source"),new ResolvedParameter<IRepositorySesison>("Destination")}));
//Now resolve

ERunOptions dataCopierType = ExtractParams(args);
IDataCopier dataCopier = container.Resolve<IDataCopier(dataCopierType.ToString());
dataCopier.DetectChanges();
dataCopier.ParseData();
dataCopier.CopyData();

DataCopier Class

class ScheduleDataCopier : IDataCopier
{
    private List<Site> _sites;
    private List<SitesAndApparatuses> _scheduleList;
    private IRepositorySession _source;
    private (IRepositorySession _destination;

    public ScheduleDataCopier(IRepositorySession source, (IRepositorySession destination)
    {
        _source=source;
        _destination=destination;
        _scheduleList = new List<SitesAndApparatuses>();
    }

    //check if new sites registration has arrived in tblSites on down from web db.
    public bool DetectChanges()
    {
        SiteAudit lastSite = new SitesAuditRepository().GetLatest();
        var sitesRepo = new SitesRepository();
        var sites = sitesRepo.Where(x => x.SID > lastSite.SALatestSID);

        if (sites.Count() < 1)
        {
            return false;
        }
        _sites = sites.ToList();
        _source.DoSomething();
        _source.CommitAndReleaseResources();//clean up but leave object reusable
        return true;
    }

    //parse the data into a list of object SitesAndApparatuses
    public bool ParseData()
    {
        try
        {
            foreach (Site s in _sites)
            {
                var schedule = (SitesAndApparatuses)XmlObjectBuilder.Deserialize(typeof(SitesAndApparatuses), s.XMLFile);
                schedule.acCode = s.Registration.RAcCode;
                _scheduleList.Add(schedule);
            }
        }
        catch (Exception ex)
        {
            throw new NotImplementedException("HANDLE THIS SHIT!", ex);
        }
        return true;
    }

    public bool CopyData()
    {
        try
        {
            var licensingScheduleRepo = new LicensingScheduleRepository();
            //some logic
            _desitnation.Commit();
        }
        catch (Exception ex)
        {
            //handle exception
        }
        return true;
    }
}

您正在执行的操作与上述操作之间的两个主要区别是,我正在使用Injection Parameters(ResolvedParameter类)在需要时动态解析对象的实例。

这让我可以让Unity为我完成整个DI过程,包括解析我的DataCopier。如果我添加另一个Datacopier,我只需要将新的DataCopier类型添加到Unity,其名称与相应的ERunOptions类型匹配,我就能够解析新的DataCopier,而不需要更改我的代码:

container.RegisterType<IDataCopier,RandomDataCopier>("0",new InjectionConstructor(new[] {new ResolvedParameter<IRepositorySession("RandomSource"),new ResolvedParameter<IRepositorySesison>("RandomDestination")}));

ERunOptions dataCopierType = ExtractParams(args);
IDataCopier dataCopier = container.Resolve<IDataCopier(dataCopierType.ToString());
dataCopier.DetectChanges();
dataCopier.ParseData();
dataCopier.CopyData();

保持相同但可以处理ScheduledDataCopier或RandomDataCopier