编程语言
首页 > 编程语言> > 使用StructureMap.DependencyInjection在C#dotnet core 2.0中进行简单的代理类依赖注入

使用StructureMap.DependencyInjection在C#dotnet core 2.0中进行简单的代理类依赖注入

作者:互联网

我使用dotnet core 2.0和StructureMap.Microsoft.DependencyInjection进行IoC和依赖注入.我正在尝试创建一个代理类进行验证.我想暗示给国际奥委会的DI使用ComponentDataAccessorProxy只要使用IComponentDataAccessor也满足ComponentDataAccessorProxy依赖是ComponentDataAccessor并满足它的依赖是IMongoDatabase没有进入循环依赖例外.我想知道是否有可能.任何帮助将不胜感激.

这是界面:

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

这是具体的定义或具体类型:

public class ComponentDataAccessor : IComponentDataAccessor
{
    private readonly IMongoDatabase _database;

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

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

最后这是一个代理类:

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);
    }
}

尝试失败:

var container = new Container();

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

    // failed attempt #2
    config.For<IComponentDataAccessor>().Use<ComponentDataAccessorProxy>();
});

解决方法:

根据文档here,你应该使用这样的东西:

config.For<IComponentDataAccessor>().DecorateAllWith<ComponentDataAccessorProxy>();
config.For<IComponentDataAccessor>().Use<ComponentDataAccessor>();

标签:c,dependency-injection,proxy,net-core,structuremap
来源: https://codeday.me/bug/20190701/1348001.html