这是一个 Web API 2 项目。
当我使用 Ninject 实现 DI 时,我收到一条错误消息
尝试创建类型为“TokenController”的控制器时发生错误。确保控制器有一个无参数的公共构造函数。
[assembly: OwinStartup(typeof(Web.Startup))]
namespace Web
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
ConfigureWebApi(app);
}
}
}
public class TokenController : ApiController
{
private IUserService _userService;
public TokenController(IUserService userService)
{
this._userService = userService;
}
[Route("api/Token")]
public HttpResponseMessage PostToken(UserViewModel model)
{
if (_userService.ValidateUser(model.Account, model.Password))
{
ClaimsIdentity identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, model.Account));
AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
var currentUtc = new SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<object>(new
{
UserName = model.Account,
AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket)
}, Configuration.Formatters.JsonFormatter)
};
}
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
当我添加<add key="owin:AutomaticAppStartup" value="false" />
到 web.config
Ninject 工作正常,但Startup.OAuthBearerOptions.AccessTokenFormat变为 null
如何在 OWIN 中使用 DI 容器?
更新
实现 IDependencyResolver 并使用 WebAPI Dependency Resolver,如下所示
public void ConfigureWebApi(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.DependencyResolver = new NinjectDependencyResolver(NinjectWebCommon.CreateKernel());
app.UseWebApi(config);
}
在简单的喷油器情况下
public void ConfigureWebApi(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
var container = new Container();
container.Register<IUserService, UserService>();
config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
app.UseWebApi(config);
}