1

ここにあるバインディングの方法を使用しようとしていますが、運がありません https://github.com/ninject/ninject.extensions.factory/wiki/Factory-interface https://github.com/ninject/ninject.extensions 。 factory/wiki/Factory-interface%3A-参照名付きバインディング

このようにしようとしているわけではないことに注意してください: 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

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 に答える