Đây là dự án API Web 2.Cách sử dụng vùng chứa DI khi OwinStartup
Khi tôi thực hiện DI sử dụng Ninject, tôi nhận được một thông báo lỗi
Có lỗi xảy ra khi cố gắng để tạo ra một bộ điều khiển của loại 'TokenController'. Đảm bảo rằng bộ điều khiển có một hàm tạo công khai không tham số.
[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);
}
}
Khi tôi thêm <add key="owin:AutomaticAppStartup" value="false" />
để web.config
Ninject hoạt động tốt, nhưng Startup.OAuthBearerOptions.AccessTokenFormat trở thành vô giá trị
Làm thế nào để sử dụng DI container với OWIN?
CẬP NHẬT
Thực hiện IDependencyResolver và sử dụng WebAPI phụ thuộc Resolver như sau
public void ConfigureWebApi(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.DependencyResolver = new NinjectDependencyResolver(NinjectWebCommon.CreateKernel());
app.UseWebApi(config);
}
Trong trường hợp Injector Simple
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);
}
SimpleInjectorWebApiDependencyResolver
Có lý do nào khiến bạn không thể thêm một hàm tạo trống vào bộ điều khiển của mình không? –
@NikolaiSamteladze Tôi đã thực hiện tiêm phụ thuộc vào hàm tạo rỗng, tôi chỉ muốn biết cách sử dụng vùng chứa DI trong trường hợp này là –
[Có một dự án] (https://github.com/DotNetDoodle/DotNetDoodle.Owin.Dependencies) cung cấp hỗ trợ này, nhưng có thể bạn sẽ phải viết bộ điều hợp cho chính mình vì nó cung cấp khả năng thực hiện hộp chỉ cho autofac. –