アップ、これは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)));
}
}
ただし、このコードを実行する前に、型マッピングを登録する必要があります
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;
}