我想在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));
感谢任何帮助。