在Unity和ASP.NET MVC中执行属性注入的方法如下:
IMyService
和实现类MyService
。public interface IMyService
{
string GetData();
}
public class MyService : IMyService
{
public string GetData()
{
return "Hello from MyService!";
}
}
HomeController
中添加一个IMyService
属性。public class HomeController : Controller
{
[Dependency]
public IMyService MyService { get; set; }
public ActionResult Index()
{
ViewBag.Message = MyService.GetData();
return View();
}
}
MyService
实现类并将其映射到IMyService
接口。var container = new UnityContainer();
container.RegisterType<IMyService, MyService>();
public class UnityDependencyAttribute : Attribute, IDependencyResolver
{
private readonly IUnityContainer _container;
public UnityDependencyAttribute(IUnityContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return _container.ResolveAll(serviceType);
}
catch
{
return new List<object>();
}
}
}
var container = new UnityContainer();
container.RegisterType<IMyService, MyService>();
DependencyResolver.SetResolver(new UnityDependencyAttribute(container));
现在,在ASP.NET MVC中使用Unity和属性注入时,HomeController
将自动注入MyService
实现类。这样,您就可以在ASP.NET MVC中使用Unity和属性注入来执行依赖注入了。
领取专属 10元无门槛券
手把手带您无忧上云