0

如何将依赖项注入CompositeControl

我尝试了以下方法 - MyServerControl 的 Calculate 仍然为空。

谢谢!

public class MyServerControl : CompositeControl
{
    private TextBox TextBox1;
    private TextBox TextBox2;
    private Label Label1;

    [Inject] // **** This is null **** 
    public ICalculate Calculate { get; set; }

    protected override void CreateChildControls()
    {
        TextBox1 = new TextBox {ID = "TextBox1", Text = "1"};
        Controls.Add(TextBox1);

        TextBox2 = new TextBox {ID = "TextBox2", Text = "2"};
        Controls.Add(TextBox2);

        var button1 = new Button {ID = "Button1", Text = "Calculate"};
        button1.Click += button1_Click;
        Controls.Add(button1);

        Label1 = new Label {ID = "Label1"};
        Controls.Add(Label1);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int value1 = Int32.Parse(TextBox1.Text);
        int value2 = Int32.Parse(TextBox2.Text);

        Label1.Text = "Result:" + Calculate.Add(value1, value2);
    }
}

public interface ICalculate
{
    int Add(int x, int y);
}

public class Calculate : ICalculate
{
    public int Add(int x, int y)
    {
        return x + y;
    }
}

NuGet 的默认 Ninject.Web.Common 引导程序:

using System.Net.NetworkInformation;

[assembly: WebActivator.PreApplicationStartMethod(typeof(NinjectDemo.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(NinjectDemo.App_Start.NinjectWebCommon), "Stop")]

namespace NinjectDemo.App_Start
{
    using System;
    using System.Web;

    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;

    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()
        {
            IKernel kernel = new StandardKernel();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            RegisterServices(kernel);
            return kernel;
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<ICalculate>().To<Calculate>().InSingletonScope();
        }        
    }
}

更新:

我无法在 Page_Load 中获取内核实例。我错过了什么吗?

<my:MyServerControl ID="MyServerControl1" runat="server" />

public partial class Default : Page
{
    [Inject]
    public ICalculate _calculate { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        kernel.Inject(MyServerControl1); // kernel is not available
    }
}

在此处输入图像描述

4

3 回答 3

2

我认为您可以只使用满足对现有对象的依赖关系的功能。在这种特殊情况下,在任何使用您的控件的上下文中,您只需调用

kernel.Inject( myControl );

其中 myControl 是复合控件的现有实例。这必须从后面的代码中调用,在已经创建实例的管道中的某处。Page_Load 很可能没问题。

编辑:有很多方法可以解决应用程序中的任何位置。例如,您可以拥有一个全球服务定位器。但是由于您使用的是引导程序,您应该能够在任何地方解析您的内核

 var kernel = (IKernel)Bootstrapper.Container;
于 2013-11-04T19:14:33.580 回答
1

您的默认页面不知道 NinjectWebCommon 类的存在。它也无法知道作为 NinjectWebCommon.CreateKernel() 方法成员的内核变量。最简单的解决方案如下:

public static class NinjectWebCommon 
{
    ...
    private static IKernel kernel;

    public static IKernel CreateKernel()
    {
        if(kernel != null)
            return kernel;

        kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);
        return kernel;
    }
    ...
}

public partial class Default : Page
{
    [Inject]
    public ICalculate _calculate { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        NinjectWebCommon.CreateKernel().Inject(MyServerControl1);
    }
}

另一种方法是使用忍者魔法。您的应用程序类可能需要从 Ninject 提供的类继承。在MVC中,它是一个 NinjectHttpApplication 类,它覆盖了引导程序。比你可能会接受 Wiktor 的回答。

老实说,我不喜欢 Ninject 魔法,因为它有时对我不起作用,而且很难找出原因。在我的MVC应用程序中,我最终创建了自己的 ConfrollerFactory,它显式地注入了依赖项。如果您想更改 IOC 容器,也可能会很痛苦。

于 2013-11-09T13:30:20.957 回答
0

您需要注册您的 Ioc 配置,请参见示例:

public static void RegisterIoc(HttpConfiguration config)
        {
            var kernel = new StandardKernel(); // Ninject IoC

            kernel.Bind<IMyService>().To<MyService>();

            // Tell WebApi how to use our Ninject IoC
            config.DependencyResolver = new NinjectDependencyResolver(kernel);
        }

public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
    {
        private IKernel kernel;

        public NinjectDependencyResolver(IKernel kernel)
            : base(kernel)
        {
            this.kernel = kernel;
        }

        public IDependencyScope BeginScope()
        {
            return new NinjectDependencyScope(kernel.BeginBlock());
        }
    }

public class NinjectDependencyScope : IDependencyScope
    {
        private IResolutionRoot resolver;

        internal NinjectDependencyScope(IResolutionRoot resolver)
        {
            Contract.Assert(resolver != null);

            this.resolver = resolver;
        }

        public void Dispose()
        {
            var disposable = resolver as IDisposable;
            if (disposable != null)
                disposable.Dispose();

            resolver = null;
        }

        public object GetService(Type serviceType)
        {
            if (resolver == null)
                throw new ObjectDisposedException("this", "This scope has already been disposed");

            return resolver.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            if (resolver == null)
                throw new ObjectDisposedException("this", "This scope has already been disposed");

            return resolver.GetAll(serviceType);
        }
    }

在你的 App_start 文件夹中添加这个类,然后在 Global.asax.cs 中写入:

// Tell WebApi to use our custom Ioc (Ninject)
            IocConfig.RegisterIoc(GlobalConfiguration.Configuration); 
于 2013-11-02T08:06:30.437 回答