Ups,這是我在使用ASP.NET Web API時的做法,不知道這是否適用於MVC控制器。但是可以使用Unity.MVC(v3或v4或v5)lib(Unity.Mvc4)! 你可以像這樣連接它,你應該在Application_Start事件中調用這個代碼!
public static class WebApiBootstrapper
{
public static void Init(IUnityContainer container)
{
GlobalConfiguration.Configure(config =>
{
config.DependencyResolver = new WebApiDependencyResolver(container); // DI container for use in WebApi
config.MapHttpAttributeRoutes();
WebApiRouteConfig.RegisterRoutes(RouteTable.Routes);
});
// Web API mappings
// All components that implement IDisposable should be
// registered with the HierarchicalLifetimeManager to ensure that they are properly disposed at the end of the request.
container.RegisterType<IYourController, YourController>(
new HierarchicalLifetimeManager(), new InjectionConstructor(typeof(IMyDataBase)));
}
}
但運行t這代碼之前,你必須註冊類型映射
container.RegisterType<IMyDatabse, MyDataBase>();
而且你還必須實現DependencyResolver類:
public class WebApiDependencyResolver : IDependencyResolver
{
protected IUnityContainer container;
public WebApiDependencyResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}
public IDependencyScope BeginScope()
{
var child = container.CreateChildContainer();
return new WebApiDependencyResolver(child);
}
public void Dispose()
{
container.Dispose();
}
}
在你的控制器:
public class YourController : ApiController, IYourController
{
IDataBase _db;
public PlayGroundController(IDataBase db)
{
_db = db;
}
非常感謝!這看起來非常好。現在,你會在MyAction中返回什麼?如果我想根據userValue更新用戶,我需要知道是否返回錯誤或重定向。在這種情況下,MyAction可以依賴用戶嗎? –
@JorgeZuverza當然可以。如果出現錯誤,請將要顯示的數據(可能是視圖模型(也可能只是一個字符串))返回到視圖。 – Shyju