Interface capture

I'm trying to make something like an interface IAuditablethat acts like a Ninject token to intercept calls.

Suppose I have the following:

public interface IAuditable
{

}

public interface IProcessor
{
    void Process(object o);
}

public class Processor : IProcessor, IAuditable
{
    public void Process(object o)
    {
        Console.WriteLine("Processor called with argument " + o.ToString());
    }
}

With this setting:

NinjectSettings settings = new NinjectSettings() { LoadExtensions = true };
IKernel kernel = new StandardKernel(settings);
kernel.Bind<IAuditAggregator>().To<AuditAggregator>().InThreadScope();
kernel.Bind<IAuditInterceptor>().To<AuditInterceptor>();

kernel.Bind(x =>
            x.FromThisAssembly()
            .SelectAllClasses()
            .InheritedFrom<IAuditable>()
            .BindToDefaultInterfaces() //I suspect I need something else here
            .Configure(c => c.Intercept().With<IAuditInterceptor>()));
kernel.Bind<IProcessor>().To<Processor>();

Whenever I try kernel.Get<IProcessor>();, I get an exception saying that several bindings are available.

If I delete kernel.Bind<IProcessor>().To<Processor>(), then it works as expected, but it is possible that you may have IProcessorone that does not implement IAuditable.

Am I on the right track?

Edit: As I said, I tried using the attribute:

public class AuditableAttribute : Attribute
{

}
[Auditable]
public class Processor : IProcessor
{

    public void Process(object o)
    {
        Console.WriteLine("Processor called with argument " + o.ToString());
    }
}
//in setup:
kernel.Bind(x =>
            x.FromThisAssembly()
            .SelectAllClasses()
            .WithAttribute<AuditableAttribute>()
            .BindDefaultInterface()
            .Configure(c => c.Intercept().With<IAuditInterceptor>()));

This leads to the same duplication problem as when using the interface.

+4
source share
1

, IAuditable, .

        kernel.Bind(x =>
            x.FromThisAssembly()
                .SelectAllClasses()
                .InheritedFrom<IAuditable>()
                .BindDefaultInterfaces()
                .Configure(c => c.Intercept().With<IAuditInterceptor>()));

        kernel.Bind(x =>
            x.FromThisAssembly()
                .SelectAllClasses()
                .InheritedFrom<IProcessor>()
                .Where(t => !typeof(IAuditable).IsAssignableFrom(t))
                .BindDefaultInterfaces());
+1

Source: https://habr.com/ru/post/1683016/


All Articles