C# 为什么不在类中创建新对象

C# 为什么不在类中创建新对象,c#,asp.net,asp.net-mvc,inversion-of-control,ninject,C#,Asp.net,Asp.net Mvc,Inversion Of Control,Ninject,我有一个Web表单/MVC混合项目,它使用Ninject作为IoC容器。直到今天,我和Ninject都没有问题。我遇到的问题是,无论何时使用类,我都无法让Ninject更新某些对象。以下是一些有效的代码: My Setup: Visual Studio 2013 Web Forms/MVC project C# Ninject 3.2.0.0 Entity Framework 下面是一些无法使用类的代码: // Master1.master namespace TestCode { p

我有一个Web表单/MVC混合项目,它使用Ninject作为IoC容器。直到今天,我和Ninject都没有问题。我遇到的问题是,无论何时使用类,我都无法让Ninject更新某些对象。以下是一些有效的代码:

My Setup:
Visual Studio 2013
Web Forms/MVC project
C#
Ninject 3.2.0.0
Entity Framework
下面是一些无法使用类的代码:

// Master1.master
namespace TestCode
{
    public partial class Master1 : MasterPage
    {
        [Inject]
        public FooController Foo { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            // Do some setup logic.
            Foo.Bar();
        }
    }
}

我的问题是,当我执行SomeMethod时,Foo为null。为什么会这样?我能做些什么才能让Ninject成为新的up Foo

好的-我现在开始工作了。谢谢大家!我需要在NinjectWebCommon类中添加一个绑定,如下所示:

// Master1.master
namespace TestCode
{
    public partial class Master1 : MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            new Wrapper().SomeMethod();
        }
    }
}

// Wrapper.cs
namespace TestCode
{
    public class Wrapper
    {
        [Inject]
        public FooController Foo { get; set; }

        public void SomeMethod()
        {
            // Do some setup logic.
            Foo.Bar();
        }
    }
}

非常确定您需要使用Ninject来提供您的对象。仅仅调用new不会进行任何注入,因为Ninject从未运行过,也没有任何东西告诉Ninject运行并注入。您需要从Ninject内核获取包装器类,而不是新建它。关键字new很好地表明您已经偏离了DI路径。Ninject不会神奇地覆盖新关键字。
public static class NinjectWebCommon 
{
    private static readonly Bootstrapper Bootstrapper = new Bootstrapper();

    public static void Start() 
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        Bootstrapper.Initialize(CreateKernel);
    }

    public static void Stop()
    {
        Bootstrapper.ShutDown();
    }

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


        // Needed to add this binding.
        kernel.Bind<IWraper>().To<Wraper>().InRequestScope();


        RegisterServices(kernel);
        GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

        return kernel;
    }
}