与asp.net mvc统一,使用属性注入传递参数

时间:2011-05-11 11:33:54

标签: 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, SystemProxyServiceEx>();

现在,我需要将一些参数传递给SystemProxyServiceEx构造函数。这些包括存储在会话变量(HttpSessionStateBase Session)中的一些值,这些值在身份验证期间存储。我该如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

常见的做法是将它们包装在一个类中并根据接口注入它。例如:

// 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>();