MvcContrib Windsor Setup Component With Parameter
Asked Answered
C

1

2

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"

Catechin answered 24/2, 2010 at 16:32 Comment(1)
please fix the code formattingStinko
S
4

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.

Stinko answered 24/2, 2010 at 17:26 Comment(1)
Thanks I had just found that and got it working so I am glad you confirmed it for me.Catechin

© 2022 - 2024 — McMap. All rights reserved.