首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >带有Db上下文的.NET核心DI子范围

带有Db上下文的.NET核心DI子范围
EN

Stack Overflow用户
提问于 2021-04-09 13:35:09
回答 1查看 208关注 0票数 1

(我正在编写一个处理器,用于处理队列中的请求(控制台应用程序)。

我想使用.NET核心DI。

到目前为止,我的代码如下所示:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
...
var connectionString = exportConfiguration.ConnectionString;

using (var scope = _serviceProvider.CreateScope())
{
   var provider = scope.ServiceProvider;
   var service = provider.GetRequiredService<MyContext>();

   service.SqlConnectionString = sqlConnectionString; // I don't think property injection on a dbcontext will work, it takes its connection string in via the constructor
}

我读过如何为对象分配参数,如上面所示,但是如何根据服务使用的所有对象中使用的连接字符串创建新上下文(使用构造函数注入,因为这就是为什么object在构造函数中使用连接字符串)?

(顺便说一下,我没有将连接字符串存储在队列中,而是从队列中下来一段代码,然后我的应用程序选择要使用的连接字符串)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-14 11:16:32

我已经设法解决了这个问题。关键是当您使用CreateScope(),然后使用GetRequiredService()时,DI系统将提供新的对象。所以我只需要提供正确的信息。现在我的代码就是这样的:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
// Prior code gets information from a queue, which could be different every time.
// This needs passing as a constructor to the DbContext and possibly other information from the queue to other methods constructors
// (constructor injection not property injection)

var connectionString = queueItem.ConnectionString;

// save the connection string so the DI system (startup.cs) can pick it up
Startup.ConnectionString = connectionString;

using (var scope = _serviceProvider.CreateScope())
{
   var provider = scope.ServiceProvider;

   var service = provider.GetRequiredService<IMyService>();

   // go off and get data from the correct dbcontext / connection string
   var data = service.GetData();

   // more processing
}

/// The Service has the DbContext in its constructor:
public class MyService : IMyService {
    private DbContext _dbContext;
    public MyService(DbContext dbContext) {
        _dbContext = dbContext;
    }

    // more stuff that uses dbcontext
}

/// In startup.cs:
public static string ConnectionString {get;set;}
...
builder.Services.AddScoped<IMyService, MyService>();
builder.Services.AddScoped<DbContext>(options => options.UseSqlServer(Startup.ConnectionString));

// Also the following code will work if needed:
// Parameter1 is something that comes from the queue and could be different for each
// CreateScope()
build.Services.AddScoped<IMyOtherService>((_) => 
   new MyOtherService(Startup.Parameter1));

我希望这能帮上忙,因为当我在谷歌上搜索的时候,我找不到该怎么做。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67028576

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文