![](/img/trans.png)
[英]What's the correct way to create class in JavaScript and pass that to MVC controller
[英]What's the correct way to instantiate an IRepository class from the Controller?
我有以下項目布局:
MVC UI
|...CustomerController (ICustomerRepository - how do I instantiate this?)
Data Model
|...ICustomerRepository
DAL (Separate Data access layer, references Data Model to get the IxRepositories)
|...CustomerRepository (inherits ICustomerRepository)
說ICustomerRepository repository = new CustomerRepository();
的正確方法是什么ICustomerRepository repository = new CustomerRepository();
當Controller無法看到DAL項目時? 或者我這樣做完全錯了?
您可以使用IoC容器通過注冊您自己的控制器工廠來解析映射,該工廠允許容器解析控制器 - 容器將解析控制器類型並注入接口的具體實例。
使用Castle Windsor的示例
在MvcApplication
類的global.asax中:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory());
}
WindsorControllerFactory
類
using System;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Core.Resource;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
public class WindsorControllerFactory : DefaultControllerFactory
{
WindsorContainer container;
public WindsorControllerFactory()
{
container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
foreach (Type t in controllerTypes)
container.AddComponentWithLifestyle(t.FullName, t, Castle.Core.LifestyleType.Transient);
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
// see http://stackoverflow.com/questions/1357485/asp-net-mvc2-preview-1-are-there-any-breaking-changes/1601706#1601706
if (controllerType == null) { return null; }
return (IController)container.Resolve(controllerType);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.