Asp.net mvc 3 Unity与asp.net mvc,通过属性注入传递参数
我目前正在mvc控制器中插入一个依赖项,如下所示:Asp.net mvc 3 Unity与asp.net mvc,通过属性注入传递参数,asp.net-mvc-3,dependency-injection,unity-container,Asp.net Mvc 3,Dependency Injection,Unity Container,我目前正在mvc控制器中插入一个依赖项,如下所示: public class HomeController : Controller { [Dependency] public IProxyService ProxyService { get; set; } } 在global.asax中,使用 UnityContainer _container = new UnityContainer(); _container.RegisterType<IProxyService,
public class HomeController : Controller
{
[Dependency]
public IProxyService ProxyService { get; set; }
}
在global.asax中,使用
UnityContainer _container = new UnityContainer();
_container.RegisterType<IProxyService, SystemProxyServiceEx>();
UnityContainer\u container=newunitycontainer();
_container.RegisterType();
现在,我需要向SystemProxyServiceEx构造函数传递一些参数。其中包括一些存储在会话变量(HttpSessionStateBase session)中的值,这些值在身份验证期间存储。如何实现这一点?通常的做法是将它们封装在类中,并基于接口注入。例如:
// This interface lives in a service or base project.
public interface IUserContext
{
string UserId { get; }
// Other properties
}
// This class lives in your Web App project
public class AspNetUserContext : IUserContext
{
public string UserId
{
get { return (int)HttpContext.Current.Session["Id"]; }
}
// Other properties
}
现在,您可以使您的SystemProxyServiceEx
依赖于IUserContext
。最后一步是注册,这当然很简单:
_container.RegisterType<IUserContext, AspNetUserContext>();
\u container.RegisterType();
为什么不在家庭控制器中使用构造函数注入?这样,您就可以从应用程序中删除对Unity容器的依赖。谢谢!我试过了,但还是有问题。一些会话变量(如loggedinuser等)实际上是在执行身份验证的我的帐户控制器中初始化的。调用的_container.RegisterType当前位于global.asax的应用程序_Start()事件中,因此当unity尝试在开始时解决依赖关系时,在AspNetUserContext类中,HttpContext.Current.Session此时为空。是否有任何方法可以在此处执行延迟加载,以便在身份验证完成后进行此调用。@user748526:Unity不会调用AspNetUserContext
类上的属性,因此只要用户未经身份验证时不使用属性,就不会出现问题。你甚至可以添加一个IsUserAuthenticated
属性。啊哈!我现在明白了!非常感谢@Steven:)