如何在Unity和asp.net mvc3中使用属性注入?

时间:2011-10-03 13:51:19

标签: asp.net-mvc-3 dependency-injection unity-container property-injection

我想在MVC3应用程序中使用属性注入。我已经将Unity 2配置为DI容器,一切都可以通过构造函数注入完成,但我无法弄清楚如何使用属性注入。我使用[Dependency]属性标记了属性,但它不起作用。

public class UnityDependencyResolver : IDependencyResolver
{
    IUnityContainer _container;


    public UnityDependencyResolver(IUnityContainer container)
    {
        _container = container;
    }


    public object GetService(Type serviceType)
    {
        try
        {
            return _container.Resolve(serviceType);
        }
        catch (Exception)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _container.ResolveAll(serviceType);
        }
        catch (Exception)
        {
            return new List<object>();
        }
    }
}

在Global.asax中,我有以下内容:

var container = new UnityContainer(); 

        var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
        section.Configure(container);

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));

感谢任何帮助。

0 个答案:

没有答案