ServiceStack - 注入属性

时间:2015-10-09 13:15:14

标签: servicestack inversion-of-control

我对Funq容器感到非常困惑。

我有以下内容:

public interface IConnectionString
{
     string ConnectionString { get; set; }

}

public class FoundationConnection : IConnectionString
{
    public FoundationConnection(string connectionString)
    {
        ConnectionString = connectionString;
    }
    public string ConnectionString { get; set; }
}

现在在我的AppHost中,我想注册

   container.Register<IConnectionString>(c=> new FoundationConnection(AppSettings.Get(
                        "FoundationConnectionString", "").MapHostAbsolutePath()));

在我的ServiceInterface中,我想以某种方式调用这个注入的方法:

 public class ServiceInterface : Service
 {
  public IConnectionString foundationConnection { get; set; }

     public object Any(SomeRequest request)
     {

         string injectedProperty = foundationConnection.ConnectionString;
      }
  }
}

问题是foundationConnection为null且从不注入。

我希望这有道理吗?

1 个答案:

答案 0 :(得分:1)

我个人会使用AppSettings来访问配置设置,这样您就可以从number of different and cascading configuration sources获取配置。

但我已经使用以下类型对此进行了测试:

public interface IConnectionString
{
    string ConnectionString { get; }
}

class FoundationConnectionString : IConnectionString
{
    public FoundationConnectionString(string connectionString)
    {
        ConnectionString = connectionString;
    }

    public string ConnectionString { get; set; }
}

它在AppHost.Configure()中注册后正常工作:

public override void Configure(Container container)
{
    container.Register<IConnectionString>(c => 
        new FoundationConnectionString("My Connection"));
}

并从测试服务访问它:

[Route("/test")]
public class Test : IReturn<string> { }

public class TestService : Service
{
    public IConnectionString Config { get; set; }

    public object Any(Test request)
    {
        return Config.ConnectionString;
    }
}

返回&#34;我的连接&#34;什么时候叫。