gpt4 book ai didi

c# - 从 Controller 实例化 IRepository 类的正确方法是什么?

转载 作者:行者123 更新时间:2023-11-30 17:22:18 26 4
gpt4 key购买 nike

我有以下项目布局:

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)

当 Controller 对 DAL 项目不可见时,ICustomerRepository repository = new CustomerRepository(); 的正确表达方式是什么?还是我这样做完全错了?

最佳答案

您可以使用 IoC 容器为您解析映射,方法是注册您自己的 Controller 工厂,允许容器解析 Controller - 容器将解析 Controller 类型并注入(inject)接口(interface)的具体实例。

示例使用 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);
}
}

关于c# - 从 Controller 实例化 IRepository 类的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2795527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com