MvcContrib Windsor Setup Component With Parameter

微笑、不失礼 提交于 2019-12-24 05:58:05

问题


I am using the MvcContrib library with Castle Windsor and I am having a problem with setting a parameter when I register a component.

I have the following interfaces for classes that wrap a DataContext. I want to be able to specify which DataContext to use for different services because I am connecting to several databases to retrieve data.

public interface IDataContext
{
    DataContext Context { get; }
}

public interface IReportingDC : IDataContext
{
}

public class Repository<T> : IRepository<T> where T : class
{

public IDataContext DC { get; set; }

  public Repository(IDataContext dataContext)
  {
    DC = dataContext;
  }
}

Here are the registration lines from my global.asax.cs.

container.AddComponentLifeStyle<IDataContext, MainDataContext>(Castle.Core.LifestyleType.PerWebRequest);

container.AddComponentLifeStyle<IReportingDC, ReportingDC>(Castle.Core.LifestyleType.PerWebRequest);

container.Register(Component.For<IRepository<ReportingTotals>>()
.ImplementedBy<Repository<ReportingTotals>>()
.Parameters(Parameter.ForKey("dataContext").Eq("IReportingDC"))
.LifeStyle.PerWebRequest
);

When I try and load the page I get the following error.

"Key invalid for parameter dataContext. Thus the kernel was unable to override the service dependency"


回答1:


Name your component and use ServiceOverrides instead of Parameters:

Component.For<IReportingDC>()
         .ImplementedBy<ReportingDC>()
         .Named("IReporting")
         .LifeStyle.PerWebRequest

and

Component.For<IRepository<ReportingTotals>>()
         .ImplementedBy<Repository<ReportingTotals>>()
         .ServiceOverrides(ServiceOverride.ForKey("dataContext").Eq("IReporting"))

See the fluent API docs for reference.



来源:https://stackoverflow.com/questions/2327664/mvccontrib-windsor-setup-component-with-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!