コントローラーからIREPositoryクラスをインスタンス化する正しい方法は何ですか?
-
04-10-2019 - |
質問
次のプロジェクトレイアウトがあります。
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();
コントローラーがDALプロジェクトに可視性がない場合?それとも私はこれを完全に間違っていますか?
解決
IOCコンテナを使用して、コンテナがコントローラーを解決できる独自のコントローラーファクトリを登録することにより、マッピングを解決できます。コンテナはコントローラータイプを解決し、インターフェイスのコンクリートインスタンスを注入します。
使用の例 キャッスルウィンザー
Global.asaxであなたの MvcApplication
クラス:
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);
}
}
所属していません StackOverflow