【问题标题】:Autofac inject singleton for SQLiteAsyncConnection with paramsAutofac 使用参数为 SQLiteAsyncConnection 注入单例
【发布时间】:2017-07-10 07:06:56
【问题描述】:

我正在使用 PCL 做一个 Xamarin Native 项目,我有一个用于定义每个平台的数据库位置的第一类:

  public class DatabaseConfiguration : IDatabaseConfiguration
    {
        public string GetConnectionString()
        {
            //This code is specific to each platform
            return PathForEachPlatform;
        }
    }

我是这样注入的:

  builder.RegisterType<DatabaseConfiguration>()
                    .As<IDatabaseConfiguration>()
                    .SingleInstance();

现在我不想将SQLiteAsyncConnection 注入我的存储库类。这个类来自这个 nugets:https://www.nuget.org/packages/sqlite-net-pcl

这是我的存储库构造函数:

    private SQLiteAsyncConnection Connection { get; }

            public SQLiteRepository(IDatabaseConfiguration configuration)
            {
                Connection = new SQLiteAsyncConnection(configuration.GetConnectionString()); // I wan't to inject the connection not create a new one.
            }
}

SQLiteAsyncConnection 没有提供接口,所以我决定使用单例。但是构造函数需要一个数据库路径。此路径由上面的另一个注入使用GetConnectionString() 方法定义。我该怎么做?

现在我有这个代码:

 builder.RegisterInstance<SQLiteAsyncConnection>()
        .WithParameter(new TypedParameter(typeof(string),"HERE THE PATH TO PASS BUT HOW ?"))
        .SingleInstance();

【问题讨论】:

    标签: c# sqlite xamarin dependency-injection


    【解决方案1】:
    builder.Register
        (c => new SQLiteAsyncConnection(
            c.Resolve<IDatabaseConfiguration>().GetConnectionString()))
        .SingleInstance();
    

    这将允许您注册连接并注入必要的连接字符串。

    【讨论】:

    • 为什么要删除 .As() ?不适合我吗?
    • 它是可选的,它不需要在那里。如果你愿意,你可以把它留在那里——它什么也没做。
    • 好的,那行不通,我会做更多检查并验证答案,非常感谢我的朋友!
    猜你喜欢
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    相关资源
    最近更新 更多