Compilation Error with Ninject

徘徊边缘 提交于 2019-12-25 04:35:13

问题


Ninject looks great, so I'd like to use it in my project. Unfortunately I am still struggling to do the most trivial binding. The [Inject] attribute compiles just fine, but the compiler cannot find the "Bind" command:

using System;
using Ninject.Core;
using Ninject.Core.Binding;

namespace NinjectTest
{
    public interface IFoo
    {
        void DoSomething();
    }

    public class Foo : IFoo
    {
        public void DoSomething()
        {
            throw new NotImplementedException();
        }
    }

    public class Bar
    {
        [Inject] private IFoo theFoo;

        public Bar()
        {
            Bind<IFoo>().To<Foo>(); //Compiler Error: "The name 'Bind' does not exist in the current context"
        }
    }
}

What could be going wrong here?


回答1:


The Bind method is a method in the Ninject StandardModule class. You need to inherit that class to be able to bind.

Here is a simple example:

using System; 
using System.Collections.Generic; 
using System.Text; 
using Ninject.Core;

namespace Forecast.Domain.Implementation 
{
    public class NinjectBaseModule : StandardModule
    {
        public override void Load()
        {
            Bind<ICountStocks>().To<Holding>();
            Bind<IOwn>().To<Portfolio>();
            Bind<ICountMoney>().To<Wallet>();
        }
    } 
}



回答2:


The Bind method is defined in ModuleBase - you should inherit your class from this or, even better, from StandardModule.




回答3:


I don't know the Ninject, but on first look I see, that the "Bind" method is not member of "Bar" class or their base class. Propably you need some instance with "Bind" method or static class with static "Bind" method.

After quick googling, I think the "Bind" method is part of instance members of "InlineMethod" class.



来源:https://stackoverflow.com/questions/1082008/compilation-error-with-ninject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!