使用具有依赖性和原始值的DryIoc

时间:2017-05-02 19:12:53

标签: c# asp.net-web-api dependency-injection dryioc

我正在注册要为接口创建的实现。这个实现构造函数有3个参数,

public ProfileImageService(ISqlConnection connection, string localStorageLocation, string serverPath)

我已经像这样注册了ISqlConnection

c.Register<Data.ISqlConnection, Data.TsqlConnection>(setup: Setup.With(openResolutionScope: true));

但是当我像这样注册ProfileImageService时

c.Register<Data.Services.Profile.IImageService, Data.Services.Profile.ProfileImageService>(Made.Of(() => new Data.Services.Profile.ProfileImageService(Arg.Index<Data.ISqlConnection>(0), Arg.Index<string>(1), Arg.Index<string>(2)), requestIgnored =>c.Resolve<Data.ISqlConnection>(), requestIgnored => localImageStoragePath, requestIgnored => localImageUrl));

我收到以下错误:

  

Message = State需要使用(可能是注入)项目   Abc.Data.TsqlConnection。要启用项目使用,您可以指定   container.With(rules =&gt;   rules.WithItemToExpressionConverter(YOUR_ITEM_TO_EXPRESSION_DELEGATE))。

我已经阅读了这个SpecifyDependencyAndPrimitiveValues并试图像它们那样重做它,但是他们的例子只用原语或依赖性来显示它,而不是两者都有,我无法找到混合时没有编译错误的语法。任何人都可以给我一些指导如何注册这个实例,指定两个字符串的值和依赖值?

1 个答案:

答案 0 :(得分:0)

以下是您的操作方式(使用最新的DryIoc v2.10.6 ):您无需在参数中指定c.Resolve<ISqlConnection>(),只需使用Arg.Of<ISqlConnection>()

using System;
using DryIoc;

public class Program
{
    public static void Main()
    {
        var c = new Container();

        var localImageStoragePath = "a";
        var localImageUrl = "b";

        c.Register<ISqlConnection, TsqlConnection>();
        c.Register<IImageService, ProfileImageService>(
            Made.Of(() => new ProfileImageService(
                Arg.Of<ISqlConnection>(), 
                Arg.Index<string>(0), 
                Arg.Index<string>(1)), 
                _ => localImageStoragePath, 
                _ => localImageUrl));

        var imgService = c.Resolve<IImageService>();

        Console.WriteLine(imgService);
    }

    public interface IImageService {}

    public class ProfileImageService: IImageService
    {
        public ProfileImageService(ISqlConnection conn, string a, string b) {}

    }

    public interface ISqlConnection {}

    public class TsqlConnection : ISqlConnection {} 
}

或者甚至更好,如果你的字符串参数不应该改变:

    c.Register<IImageService, ProfileImageService>(
        Made.Of(() => new ProfileImageService(
            Arg.Of<ISqlConnection>(), 
            localImageStoragePath, 
            localImageUrl)));

这是live proof