如何使用ninject将参数传递给客户提供者

问题描述 投票:0回答:1

我有一个名为MyRepository的服务,我要为MyRepository编写自己的自定义提供程序。如何使用提供程序将参数传递给MyRepository的构造函数?

这是我的代码:

public class MyRepository : IMyRepository
{
    private string _path;

    public MyRepository(string path)
    { 
        _path = path;
    }

    // more code...
}

public class MyRepositotyProvider : Provider<IMyRepositoty>
{
    public static IMyRepositoty CreateInstance()
    {
        return new MyRepository(/*how to pass an argument?*/);
    }

    protected override IMyRepositoty CreateInstance(IContext context)
    {
        // I need to pass path argument?
        return CreateInstance();
    }
}

// I need to pass the path argument to the provider
var instance = OrganisationReportPersisterProvider.CreateInstance(/*pass path arg*/);
c# dependency-injection ninject provider ninject-extensions
1个回答
0
投票

根据您的评论,您可以考虑使用可以传递给较低层的抽象

public interface ISomeSetting { 
    string Path { get; } 
}

然后可以通过提供者中的上下文来解析

public class MyRepositotyProvider : Provider<IMyRepositoty> {

    public static IMyRepositoty CreateInstance(string path) {
        return new MyRepository(path);
    }

    protected override IMyRepositoty CreateInstance(IContext context) {
        ISomeSetting setting = context.Kernel.Get<ISomeSetting>()
        var path = setting.Path;
        return CreateInstance(path);
    }
}

该实现将存在于更高的层中并允许去耦。

理想情况下,可以将存储库重构为依赖于抽象

public class MyRepository : IMyRepository {
    private readonly string _path;

    public MyRepository(ISomeSetting setting)  
        _path = setting.Path;
    }

    // more code...
}

并且避免需要提供者开始。

© www.soinside.com 2019 - 2024. All rights reserved.