使用Ninject在MVC 3中注入属性,可以通过以下步骤实现:
下面是一个示例代码:
Install-Package Ninject
Install-Package Ninject.MVC3
using Ninject;
using Ninject.Modules;
using Ninject.Web.Common;
public class MyNinjectModule : NinjectModule
{
public override void Load()
{
Bind<IMyService>().To<MyService>();
}
}
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernel)
{
this.kernel = kernel;
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
}
using System;
using System.Web.Mvc;
using Ninject;
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
IKernel kernel = new StandardKernel(new MyNinjectModule());
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}
}
using System.Web.Mvc;
public class HomeController : Controller
{
[Inject]
public IMyService MyService { get; set; }
public ActionResult Index()
{
MyService.DoSomething();
return View();
}
}
这样,在HomeController中就可以使用属性注入来获取IMyService的实例,而不需要在控制器中手动创建和管理依赖。
领取专属 10元无门槛券
手把手带您无忧上云