我有WebForms項目,在那裏我有WebApi控制器。 如何注入控制器構造函數和動作過濾器構造函數?統一注入到asp.net web api控制器和過濾器
我已經實現IDependencyResolver
和Global.asax
(GlobalConfiguration.Configuration.DependencyResolver
)使用它,但它並不能幫助: 請求控制器上說,沒有默認的構造函數和過濾器在應用程序啓動說,它不包含一個構造函數0個參數。
此外,我需要singletone注入行動過濾器。
謝謝。
UPD
public class ScopeContainer : IDependencyScope
{
protected readonly IUnityContainer _container;
public ScopeContainer(IUnityContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
return _container.IsRegistered(serviceType) ? _container.Resolve(serviceType) : null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.IsRegistered(serviceType) ? _container.ResolveAll(serviceType) : new List<object>();
}
public void Dispose()
{
_container.Dispose();
}
}
public class IoCContainer : ScopeContainer, IDependencyResolver
{
public IoCContainer(IUnityContainer container) : base(container)
{
}
public IDependencyScope BeginScope()
{
var child = _container.CreateChildContainer();
return new ScopeContainer(child);
}
}
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
ConfigureApi(GlobalConfiguration.Configuration);
}
void ConfigureApi(HttpConfiguration config)
{
var unity = new UnityContainer();
unity.RegisterInstance<ILogger>(new Logger());
unity.RegisterType<IRepository, DbRepository>();
config.DependencyResolver = new IoCContainer(unity);
}
private static void RegisterRoutes()
{
RouteTable.Routes.MapHttpRoute("ServiceApi", "api/{controller}/{action}");
}
}
顯示您的IDependencyResolver的實現。你如何在Unity容器中註冊類型?這裏有一個鏈接如何在WebApi中使用IDependencyResolve http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver – Jehof
是的,我閱讀這篇文章並使用它 – Boo