何不使用Web應用程序中的所有項目引用Autofac
註冊組件?如何使用Autofac在非引用項目中註冊組件
我有我的分層按以下格式應用程序:
- 網站
- 任務
- 服務
請使用下面的代碼爲我解釋。
我的控制器類:
public class MyController : Controller
{
private IMyTask myTask;
public MyController(IMyTask myTask)
{
this.myTask = myTask;
}
public ActionResult Index()
{
HomeViewModel model = myTask.Index();
return View(model);
}
}
我的任務等級:
public class MyTask : IMyTask
{
private IMyService myService;
public MyTask(IMyService myService)
{
this.myService = myService;
}
public HomeViewModel Index()
{
HomeViewModel homeViewModel = new HomeViewModel();
// Do something with myService
return homeViewModel;
}
}
我Index操作方法將調用一個方法從我的任務類,這將創造我的視圖模型,並將其返回行動方法。
我只是在每個項目中引用所需的引用,我不想引用任何不應該在那裏的項目。例如,我的網站只會引用MyProject.Tasks
。而MyProject.Tasks
只會引用MyProject.Services
。我的網站不會包含對這兩個項目的引用。
我在努力瞭解如何使用Autofac
註冊上述依賴關係,看到我沒有在我的網站中引用這兩個項目?
通常我會做這樣的Application_Start
:
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<MyTask>().As<IMyTask>().InstancePerHttpRequest();
builder.RegisterType<MyService>().As<IMyService>().InstancePerHttpRequest();
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
我已經試過這從我的網站:
builder.RegisterAssemblyTypes(Assembly.ReflectionOnlyLoad("MyProject.Services"))
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces();
...但它不會工作,因爲我沒有引用MyProject.Services
在網站上。
這樣做的最好方法是什麼?
如果你的網站不使用的服務是沒有意義註冊從任何事情。他們應該在任務項目中註冊。不確定你的設計是什麼樣的,但你可能需要在你的任務項目中引入一些初始化。 – JuhaKangas
是的,我想過,但我需要傳遞構建器實例嗎? –
嘗試創建一個或多個[模塊](https://code.google.com/p/autofac/wiki/StructuringWithModules)引用所有或這些庫的組並執行註冊的項目。 –