[英]Ninject injection in controller is null
我有一個 web api,我必須使用 Ninject 來做 DI。 我按照以下教程中的步驟操作,但仍然無法使其正常工作。
我找到的大多數解決方案都是針對舊的 ASP.Net,在 ASP.Net Core 中不起作用。
而且我知道 MVC 項目和 web-API 項目之間存在差異。
https://dev.to/cwetanow/wiring-up-ninject-with-aspnet-core-20-3hp
啟動
public class Startup
{
private readonly AsyncLocal<Scope> scopeProvider = new AsyncLocal<Scope>();
public IKernel Kernel { get; set; }
private object Resolve(Type type) => Kernel.Get(type);
private object RequestScope(IContext context) => scopeProvider.Value;
public Startup(Microsoft.Extensions.Configuration.IConfiguration configuration)
{
Configuration = configuration;
}
public Microsoft.Extensions.Configuration.IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddRequestScopingMiddleware(() => scopeProvider.Value = new Scope());
services.AddCustomControllerActivation(Resolve);
services.AddCustomViewComponentActivation(Resolve);
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
Kernel = RegisterApplicationComponents(app);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
private IKernel RegisterApplicationComponents(IApplicationBuilder app)
{
// IKernelConfiguration config = new KernelConfiguration();
Kernel = new StandardKernel(new ApplicationBusinessLogicModule(),
new DataAccessModule());
// Register application services
foreach (var ctrlType in app.GetControllerTypes())
{
Kernel.Bind(ctrlType).ToSelf().InScope(RequestScope);
}
// Here i do some more bindings
Kernel.BindToMethod(app.GetRequestService<IViewBufferScope>);
return Kernel;
}
private sealed class Scope : DisposableObject { }
}
public static class BindingHelpers
{
public static void BindToMethod<T>(this IKernel config, Func<T> method) =>
config.Bind<T>().ToMethod(c => method());
}
控制器:
[ApiController]
public class GpsController : Controller
{
[Inject]
public IGPSProcessor Processor;
[HttpPost("[Action]")]
public XmlDocument Gpsehi([FromBody]string message)
{
return Processor.Run(message);
}
}
控制器中的屬性始終為空,不應為空。
根據文檔Ninject 不再支持字段注入。 使用公共二傳手將您的領域轉換為財產,您應該很高興
[Inject]
public IGPSProcessor Processor { private get; set; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.