Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple proxy class dependency injection in C# dotnet core 2.0 using StructureMap.DependencyInjection

I am using dotnet core 2.0 and StructureMap.Microsoft.DependencyInjection for IoC and dependency injection. I am trying to creat a proxy class for validation. I am trying to imply to IoC's DI to use ComponentDataAccessorProxy whenever IComponentDataAccessor is used and also satisfy ComponentDataAccessorProxy dependency which is ComponentDataAccessor and satisfy it's dependency which is IMongoDatabase without getting into circular dependency exception. I am wondering if it is possible. Any help would be greatly appreciated.

This is interface:

public interface IComponentDataAccessor
{
    Component SaveComponent(Component componentToAdd);
}

This is concrete definition or concrete type:

public class ComponentDataAccessor : IComponentDataAccessor
{
    private readonly IMongoDatabase _database;

    public ComponentDataAccessor(IMongoDatabase database)
    {
      _database = database;
    }

    public Component SaveComponent(Component componentToAdd)
    {
        // actually save the componentToAdd
    }
}

And lastly this is a proxy class:

public class ComponentDataAccessorProxy : IComponentDataAccessor
{
    private readonly IComponentDataAccessor _componentDataAccessor;

    public ComponentDataAccessorProxy(IComponentDataAccessor componentDataAccessor)
    {
        _componentDataAccessor = componentDataAccessor;
    }

    public Component SaveComponent(Component componentToAdd)
    {
        // do some validation here, if everything is good then call 
        // concrete class otherwise throw an exception

        return _componentDataAccessor.SaveComponent(componentToAdd);
    }
}

Failed attempts:

var container = new Container();

container.Configure(config =>
{
    // failed attempt #1
    config.Forward<IComponentDataAccessor, ComponentDataAccessorProxy>();

    // failed attempt #2
    config.For<IComponentDataAccessor>().Use<ComponentDataAccessorProxy>();
});
like image 887
Node.JS Avatar asked Feb 06 '26 23:02

Node.JS


1 Answers

According to the documentation here, you should be using something like this:

config.For<IComponentDataAccessor>().DecorateAllWith<ComponentDataAccessorProxy>();
config.For<IComponentDataAccessor>().Use<ComponentDataAccessor>();
like image 125
Camilo Terevinto Avatar answered Feb 08 '26 13:02

Camilo Terevinto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!