通用存储库Loc

时间:2015-08-29 15:35:06

标签: c# castle-windsor loc

我正在学习实体框架并尝试使用工作模式的通用存储库。使用 Castle Windsor 我通过接口注入所有内容。

然而,工作单元属性InternetRepository紧密耦合:

for i in CampaignType.objects.all()
    for j in Campaign.objects.filter(name=i.name)
        print j.name

如何注入此属性以使用接口?下面是public interface IUnitOfWork { IGenericRepository<RecordInternetSpeed> InternetSpeedRepository { get; } void Save(); } public class UnitOfWork :IUnitOfWork, IDisposable { private bool disposed = false; private InternetSpeedEntities context = new InternetSpeedEntities(); private IGenericRepository<RecordInternetSpeed> internetSpeedRepository; public IGenericRepository<RecordInternetSpeed> InternetSpeedRepository { get { if(this.internetSpeedRepository == null) { this.internetSpeedRepository = new GenericRepository<RecordInternetSpeed>(context); } return internetSpeedRepository; } } public void Save() { context.SaveChanges(); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } 的调用方式:

IUnitOfWork

然后在我的程序的主要类中调用它:

    private Timer timer;
    private ICalculateInternetSpeed internetSpeed;
    private IUnitOfWork unitOfWork;

    public MyRunner(ICalculateInternetSpeed internetSpeed, IUnitOfWork unitOfWork)
    {
        this.internetSpeed = internetSpeed;
        this.unitOfWork = unitOfWork;
    }

    public void Start()
    {
        timer = new Timer
                    {
                        //1000 (1 sec)
                        Interval = 5000,
                        Enabled = true
                    };

        timer.Elapsed += (TimerElapsed);
    }

   public void Stop()
   {

   }

   private void TimerElapsed(object sender, ElapsedEventArgs e)
   {
       try
       {
           timer.Enabled = false;
           //Kick off method to get the download speed
           var speed = internetSpeed.CalculateInternetDownloadSpeed();
           Logger.Logger.Info("Internet Speed calculated.");
           unitOfWork.InternetSpeedRepository.Insert(speed);
           unitOfWork.Save();
           Logger.Logger.Info(string.Format("Inserted record with ID {0} into the database.", speed.RecordId));
       }
       catch (Exception ex)
       {
           Logger.Logger.Error(ex.ToString());
       }
       finally
       {
           timer.Enabled = true;
       }
   }
}

我认为最后一段代码片段是我的安装程序类:

private static void Main(string[] args)
    {
        container = new WindsorContainer(new XmlInterpreter());
        container.Install(FromAssembly.This());
        var runner = container.Resolve<IMyRunner>();

        HostFactory.Run(x =>
            {
                x.Service<IMyRunner>(s =>
                    {
                        s.SetServiceName(ServiceName);
                        s.ConstructUsing(c => runner);
                        s.WhenStarted(tc => tc.Start());
                        s.WhenStopped(tc =>
                            {
                                tc.Stop();
                                container.Release(runner);
                            });
                    });

                x.RunAsLocalSystem();
                x.SetDescription(ServiceDescription);
                x.SetDisplayName(ServiceDisplayName);
                x.SetServiceName(ServiceName);
                x.StartAutomatically();

            });
    }

正如你所看到的,我试图在这里注射但不确定这是否有效。这是进行属性注入的正确方法吗?

1 个答案:

答案 0 :(得分:0)

首先,请务必注册InternetSpeedEntities 然后,接受IGenericRepository<RecordInternetSpeed>作为工作单元构造函数中的参数并设置私有字段,或者将该属性转换为带有getter和setter的自动属性,Castle Windsor将为您完成工作。

但是很少有其他笔记:

  • 尝试习惯通过约定注册您的组件(例如,container.Register( Classes.FromThisAssembly() .Pick().WithServiceDefaultInterfaces()
    );
    ) 这样你就不必手动完成所有事情..
  • 注意组件的生活方式。如果您没有指定一个 - 默认情况下它是一个单身人士。那些不会被丢弃直到容器被丢弃。或者,您可以将组件的生活方式绑定到对象图上的父对象类型。

希望这有帮助,祝你好运!

-EDIT -

作为示例,您的UnitOfWork可能如下所示:

public class UnitOfWork : IUnitOfWork, IDisposable
{
    public UnitOfWork(GenericRepository<RecordInternetSpeed> repository, InternetSpeedEntities context)
    {
        this.context = context;
        this.InternetSpeedRepository = repository;
    }

    private bool disposed = false;
    private InternetSpeedEntities context;

    public IGenericRepository<RecordInternetSpeed> InternetSpeedRepository { get; private set; }

    ...

} 

你的安装程序看起来像这样:

public class Installer : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Classes.FromThisAssembly()
            .Pick().WithServiceDefaultInterfaces()
            .LifestyleTransient()
            );
    }
}  

存储库和上下文是UnitOfWork依赖项。只要windsor知道如何创建它们,它就会在解析过程中将它们提供给构造函数。