1

我正在尝试使用位于此处的绑定方法,但没有运气 https://github.com/ninject/ninject.extensions.factory/wiki/Factory-interface https://github.com/ninject/ninject.extensions。 factory/wiki/Factory-interface%3A-Reference-Named-Bindings

请记住,我不是想这样做:https : //gist.github.com/akimboyko/4593576 而是我试图使用约定 GetMercedes() 来表示

我基本上是在尝试实现这一点:https ://gist.github.com/akimboyko/4593576 ,上面的示例中指定了约定。

using Ninject;
using Ninject.Extensions.Factory;
using Ninject.Modules;
using Ninject.Parameters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Test.NinjectFactory
{
    public class Program
    {
        public static void Main()
        {
            using (var kernel = new StandardKernel(new CarModule()))
            {


               var factory = kernel.Get<ICarFactory>();
               var mercedes =factory.GetMercedes();
                int i = 1; 

            }
        }

        public interface ICar
        {
            void Drive();

        }

        public class Mercedes : ICar
        {
            readonly ICarFactory carFactory;
            public Mercedes(ICarFactory carFactory)
            {
                this.carFactory = carFactory;
            }

            public void Drive()
            {
                var Mercedes = this.carFactory.GetMercedes();
            }

        }


        public interface ICarFactory
        {
            ICar GetMercedes();
        }

        public class CarModule : NinjectModule
        {
            public override void  Load()
            {
                //https://github.com/ninject/ninject.extensions.factory/wiki/Factory-interface%3A-Referencing-Named-Bindings
                Kernel.Bind<ICarFactory>().ToFactory();
                Bind<ICar>().To<Mercedes>().NamedLikeFactoryMethod<ICarFactory>(x => x.GetMercedes());//doesnt work for me

            }
        }
    }
}
4

2 回答 2

2

我将其发布为答案,因为这很可能是原因。

工厂扩展使用前缀Get方法作为标准。Get通过使用前缀和 using调用任何工厂方法,您将遇到问题NamedLikeFactoryMethod。例如,GetFordGetMercedesGetNissan。您会注意到,在您提供的链接的示例中,该函数被调用CreateMercedes

将您的函数名称更改为CreateMercedes任何不以开头的 Get名称,应该没问题。

于 2013-06-20T22:29:35.480 回答
1

我在这里找到了答案: https ://gist.github.com/akimboyko/5338320

看来您需要一个函数来处理绑定

public class BaseTypeBindingGenerator<InterfaceType> : IBindingGenerator
{
    public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot)
    {
        if (type != null && !type.IsAbstract && type.IsClass && typeof(InterfaceType).IsAssignableFrom(type))
        {
            string.Format("Binds '{0}' to '{1}' as '{2}", type, type.Name, typeof(InterfaceType)).Dump();

            yield return bindingRoot.Bind(typeof(InterfaceType))
                                    .To(type)
                                    .Named(type.Name) as IBindingWhenInNamedWithOrOnSyntax<object>;
        }
    }
}
于 2013-06-30T16:47:45.443 回答