我正在尝试在编写的程序中使用企业库的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……这是错误的方法吗?为什么要在网上查找有关它的任何信息呢?

这可能是太多人无法阅读的代码。但是我希望得到答案!

提前致谢
尼尔

最佳答案

我会做类似的事情:

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 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

关于c# - Unity IOC和Factory模式以及存储库模式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13518866/

10-10 23:26