gpt4 book ai didi

asp.net - Unity 注入(inject)到 asp.net web api Controller 和过滤器

转载 作者:行者123 更新时间:2023-12-04 05:19:11 24 4
gpt4 key购买 nike

我有 WebForms 项目,并且有 WebApi Controller 。
如何注入(inject) Controller 构造函数和 Action 过滤器构造函数?

我已经实现了IDependencyResolver并在 Global.asax 中使用它( GlobalConfiguration.Configuration.DependencyResolver ),但它没有帮助:
请求 Controller 说没有默认构造函数,应用程序启动时的过滤器说它不包含带 0 个参数的构造函数。

此外,我需要单音注入(inject)到 Action 过滤器。

谢谢。

更新


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}");
}
}

最佳答案

我认为这可能是您注册路线的方式。

WebApi 路由在默认项目示例中通过 GlobalConfiguration.Routes 注册。而不是 RouteTable.Routes由 MVC Controller 使用。如果 MVC 路由方法错误地加载了 ApiController,它将找不到您的依赖关系解析器。

尝试将您的代码修改为:

public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(GlobalConfiguration.Configuration);
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(HttpConfiguration config)
{
config.Routes.MapHttpRoute("ServiceApi", "api/{controller}/{action}");
}

}

关于asp.net - Unity 注入(inject)到 asp.net web api Controller 和过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13860536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com