2013-06-25 45 views
0

我有一個ITestService接口。 TestService1TestService2實現ITestService。我想要的是使用TestService1 for Controller1 and TestService2 for Controller2。如何在Autofac中做到這一點?Autofac向不同的控制器註冊不同的實現

我正在使用ASP.NET MVC4。

我想這一個,但它沒有工作

builder.RegisterType<Controller1>().WithParameter(ResolvedParameter.ForNamed<ITestService>("TestService1")).InstancePerDependency(); 
builder.RegisterType<Controller2>().WithParameter(ResolvedParameter.ForNamed<ITestService>("TestService2")).InstancePerDependency(); 

我也試過這一次,沒有成功

builder.RegisterType<TestService1>().Named<ITestService>("TestService1").As<ICategoryService>(); 
    builder.RegisterType<TestService2>().Named<ICategoryService>("TestService2").As<ICategoryService>(); 

    builder.RegisterType<Nop.Web.Controllers.Controller1>().WithParameter(ResolvedParameter.ForNamed<ITestService>("TestService1")); 
    builder.RegisterType<Nop.Admin.Controllers.Controller2>().WithParameter(ResolvedParameter.ForNamed<ITestService>("TestService2")); 
+0

你的第二個例子應該工作,你會得到什麼錯誤信息?在你的示例中,你有時會寫'ITestService',有時會寫'ICategoryService',但我猜這只是你的例子中的一個錯字... – nemesv

回答

0

已分配的名稱 「TestService1」 和 「TestService2」?例如

builder.RegisterType<TestService1>().As<ITestService1>().Named("TestService1"); 
builder.RegisterType<TestService2>().As<ITestService2>().Named("TestService2"); 
+0

當我嘗試寫代碼時,出現編譯時錯誤 Service.ExtendedCategoryService,Autofac .Builder.ConcreteReflectionActivatorData,Autofac.Builder.SingleRegistrationStyle> .Named (string)'不能從用法推斷。嘗試明確指定類型參數。 –

相關問題