Внедрение данных Ninject в проект ASP.NET MVC

Я разрабатываю веб-приложение, которое использует инъекцию данных Ninject в моем проекте ASP.NET MVC5. Я установил NinjectDependencyResolver, который наследуется от IDependencyResolver следующим образом:

public class NinjectDependencyResolver : IDependencyResolver
{
    private IKernel kernel;

    public NinjectDependencyResolver(IKernel kernelParam)
    {
        kernel = kernelParam;
        AddBindings();
    }

    public object GetService(Type serviceType)
    {
        return kernel.TryGet(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return kernel.GetAll(serviceType);
    }

    private void AddBindings()
    {
       

        // here I have all my bindings set up
        kernel.Bind<ProConnect.Domain.Abstract.IMyRepository>().To<MyRepository>();

        
    }
}

а вот класс NinjectWebCommon, который запускается при запуске приложения и регистрирует службы:

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyApp.WebUI.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(MyApp.WebUI.App_Start.NinjectWebCommon), "Stop")]

namespace ProConnect.WebUI.App_Start
{
    using System;
    using System.Web;

    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;
    using Ninject.Web.Common.WebHost;

    public static class NinjectWebCommon 
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// <summary>
        /// Starts the application.
        /// </summary>
        public static void Start() 
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }

        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }

        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
                RegisterServices(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            // creating the bridge between the NinjectDependencyResolver class and the MVC support for dependency injection.
            System.Web.Mvc.DependencyResolver.SetResolver(new
                MyApp.WebUI.Infrastructure.NinjectDependencyResolver(kernel));

            // maybe I have to add some code here to create the bridge between
            // NinjectDependencyResolver class and my standard classes that 
            // have nothing to do with MVC????
        }
    }
}

Я использую это для внедрения объекта репозитория, поступающего из домена, в мои контроллеры MVC, и все это работает отлично.

У меня проблема в том, что я хотел бы внедрить некоторые другие объекты репозитория в класс настроек, который будет извлекать некоторые данные настроек из базы данных. Поскольку мой класс настроек не является контроллером MVC, а просто старым классом, он не понимает, как вводить данные.

Может ли кто-нибудь помочь мне в этом? Я попытался снова настроить инъекцию данных, но это не сработало:

public class Settings
    {



        private Domain.Abstract.ISettingRepository settingRepository;
        private StandardKernel kernel;


        public Settings()
        {
            this.kernel = new StandardKernel();
            
            // I don't know if this loads a new kernel or the one that is used in the rest of the MVC application
            kernel.Load(Assembly.GetExecutingAssembly());
            
            // I tryed re-specifying the bindings but this didn't help
            kernel.Bind<Domain.Abstract.ISettingRepository>().To<Domain.Concrete.SettingRepository>();

            this.settingRepository = kernel.Get<Domain.Abstract.ISettingRepository>();
        }
        
        public void DoSomethigWithSettings(){
            this.settingRepository.Settings()......
        }
    }

person Ephie    schedule 05.10.2020    source источник


Ответы (1)


Хорошо, я понял ответ благодаря https://stackoverflow.com/a/19585471/11011693

Я просто получил объект, который хотел внедрить в класс, отличный от MVC, из текущего MVC DependencyResolver, настроенного при запуске приложения.

public class Settings
    {
        private Domain.Abstract.ISettingRepository settingRepository;

        public Settings()
        {
            // simply get the object you want to inject in a non MVC class 
            // from the current MVC DependencyResolver that is set up on Application Start
            this.settingRepository = (Domain.Abstract.IAppSettingService)System.Web.Mvc.DependencyResolver.Current.GetService(typeof(Domain.Abstract.IAppSettingService));
        }
        
        public void DoSomethigWithSettings(){
            this.settingRepository.Settings()......
        }
    }
person Ephie    schedule 06.10.2020