yedidya sulzbacher
yedidya sulzbacher

Reputation: 63

Ninject injection in controller is null

I have a web api and I have to use Ninject to do the DI. I followed the steps in the following tutorial, but still didn't manage to get it to work.

Most of the solutions I found were for old ASP.Net, which didn't work in ASP.Net Core.

And I understand that there's a difference between MVC projects and web-API projects.

https://dev.to/cwetanow/wiring-up-ninject-with-aspnet-core-20-3hp

The startup

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

The controller:

[ApiController]
    public class GpsController : Controller
    {
        [Inject]
        public IGPSProcessor Processor;

        [HttpPost("[Action]")]
        public XmlDocument Gpsehi([FromBody]string  message)
        {
            return  Processor.Run(message);
        }
    }

The property in the controller is always null, it shouldn't be null.

Upvotes: 3

Views: 609

Answers (1)

Imantas
Imantas

Reputation: 1662

As per documentation Ninject no longer supports field injections. Convert your field to property with a public setter and you should be good to go

[Inject]
public IGPSProcessor Processor { private get; set; }

Upvotes: 2

Related Questions