gpt4 book ai didi

c# - 在 Web API 和 OWIN 中使用简单注入(inject)器

转载 作者:可可西里 更新时间:2023-11-01 08:05:27 27 4
gpt4 key购买 nike

我遇到了与 described here 相同的问题我的设置几乎是identical to this这实际上是基于 this guide .当我在我的 Controller 中访问一个方法时,我得到了这个

An error occurred when trying to create a controller of type 'TestController'. Make sure that the controller has a parameterless public constructor.

这是堆栈跟踪

at System.Web.Http.Dispatcher.DefaultHttpControllerActivator
.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor,
Type controllerType)\r\n
at System.Web.Http.Controllers.HttpControllerDescriptor
.CreateController(HttpRequestMessage request)\r\n
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

这是内部异常的堆栈跟踪

at System.Linq.Expressions.Expression.New(Type type)\r\n  
at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator
.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator
.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)

这是我的 Controller 的样子

public class TestController : ApiController
{
private readonly ITestRepo _repo;
public TestController(ITestRepo repo)
{
_repo = repo;
}

public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

public string Get(int id)
{
return _repo.GetId(id);
}
}

下面是我如何设置 Simple Injector

 public class Startup
{
public void Configuration(IAppBuilder app)
{
// Create the container as usual.
var container = new Container();
// Register your types, for instance using the RegisterWebApiRequest
// extension from the integration package:
container.RegisterWebApiRequest<ITestRepo, TestRepo>();

container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

container.Verify();

GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);

//
ConfigureOAuth(app, container);

var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
}
}

最佳答案

我遇到了同样的问题,但使用的是 UnityDependencyResolver。但我认为它也应该适用于 SimpleInjectorWebApiDependencyResolver。尝试像这样注册您的解析器(作为 HttpConfiguration 的属性):

public void Configuration(IAppBuilder app)
{
var container = GetContainer(); // Initialise container

HttpConfiguration config = new HttpConfiguration
{
DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
};

WebApiConfig.Register(config);
app.UseWebApi(config);
}

关于c# - 在 Web API 和 OWIN 中使用简单注入(inject)器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28230951/

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