Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

c# - Ninject factory create T based on enum

I want to let Ninject resolve an instance of T based on a specific enum input value.

I have read about Ninject's factory extension, but I couldn't find any example having the factory resolve a specific class based on an enum.

Each class derives from a base class and that derived class has several, different interfaces that Ninject also has to resolve.

For example this is how the interface should look like:

public interface IProcessFactory
{
    T Create<T>(ProcessIndex processIndex) where T : BaseProcess;
}

How can this be achieved ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is not supported out of the box. You can customize it by writing your own implementation of IInstanceProvider(also see ninject Wiki entry. Then configure it for your specific factory:

kernel.Bind<IFooFactory>()
      .ToFactory(() => new MyCustomInstanceProvider());

Or alternatively, if you want to change the behavior of all .ToFactory() bindings: Rebind IInstanceProvider after loading Ninject.Extensions.Factory:

kernel.Rebind<IInstanceProvider>().To<MyCustomInstanceProvider>();

However, if it's not something you need often i would consider manually writing a factory implementation @ composition root.

Anyway, in both cases you'll need to know how to create a conditional binding. Ninject calls it Contextual Binding. One method is to use Binding-Metadata:

const string EnumKey = "EnumKey";

Bind<IFoo>().To<AFoo>()
            .WithMetadata(EnumKey, MyEnum.A);

IResolutionRoot.Get<IFoo>(x => x.Get<MyEnum>(EnumKey) == MyEnum.A);

Another way would be to create a custom IParameter and use in a conditional binding:

Bind<IFoo>().To<AFoo>()
            .When(x => x.Parameters.OfType<MyParameter>().Single().Value == A);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...