Conditional Ninject Binding Based on Property Value

I'm having trouble defining bindings using ninject.

I am in a standard ASP.NET WebForms application. I have defined an http handler for embedding dependencies on pages and Property injection controls.

Here is what I am trying to do:

I am creating user combobox user controls. Based on the enumeration value on this combo box, I want to be able to introduce another object into the property (what I'm trying to do is a little more than that, but the answer to this should be enough to make me move).

+5
source share
2 answers

, , ( , ), , . , ? factory factory, Ninject .

public enum EntityType { A,B } 
public class MyControl : UserControl
{
    [Inject]
    public Func<EntityType, IMyEntityDisplayStrategy> DisplayStrategyFactory 
    { 
        get { return this.factory; }
        set { this.factory = value; this.UpdateEntityDisplayStrategy(); }
    }

    public EntityType Type 
    { 
        get { return this.type; } 
        set { this.type = value; this.UpdateEntityDisplayStrategy(); };
    }

    private UpdateEntityDisplayStrategy()
    {
        if (this.DisplayStrategyFactory != null)
            this.entityDisplayStrategy = this.DisplayStrategyFactory(this.type);
    }
}

Bind<Func<EntityType, IMyEntityDisplayStrategy>>
    .ToMethod(ctx => type => 
         type == ctx.kernel.Get<IMyEntityDisplayStrategy>( m => 
             m.Get("EntityType", EntityType.A));
Bind<IMyEntityDisplayStrategy>.To<AEntityDisplayStrategy>()
    .WithMetadata("EntityType", EntityType.A)
Bind<IMyEntityDisplayStrategy>.To<BEntityDisplayStrategy>()
    .WithMetadata("EntityType", EntityType.B)

. , .

OnActivation((ctx, instance) => 
    instance.MyStrategy = ctx.Kernel.Get<MyDependency>(m => 
        m.Get("MyConstraint", null) == instance.MyConstraint);
+10

, ( Ninject 3), , . , . ,

public enum FileFormat
{
    Pdf,
    Word,
    Excel,
    Text,
    Tex,
    Html
}

public interface IFileWriter
{
    bool Supports(FileFormat format)

    ...
}

public class FileProcessor
{
    FileProcessor(IFileWriter[] writers)
    {
        // build a dictionary with writers accepting different formats 
        // and choose them when needed
    }
}

public class MyModule : NinjectModule
{
     public override void Load()
     {
         ...

         Bind<IFileWriter>().To<PdfFileWriter>();
         Bind<IFileWriter>().To<WordFileWriter>();
         Bind<IFileWriter>().To<TexFileWriter>();
         Bind<IFileWriter>().To<TextFileWriter>();
         Bind<IFileWriter>().To<HtmlFileWriter>();
     }
}

, !

0

All Articles