您可以在中间件中创建瞬态DI服务吗?

发布于 2025-02-13 17:16:58 字数 323 浏览 1 评论 0原文

我正在调用一个购买的软件包,我没有源代码。它预计通过DI预先配置的服务。我不能改变这个。

在用户登录之前,我不知道该服务的所有参数。用户“ A”可能具有与用户“ B”不同的配置。如果没有用户登录,那么服务就必须是另一种方式。

我不能在“启动”期间注入它,因为它将以“ A”和“ B”(和“ No用户”)的方式配置不同的

位置(我认为)是在中间件“ Invoke”中进行的。 ,我似乎无法访问IservicesCollection来执行'.addtransient<>'

这甚至可能吗?

还是有更好的方法可以动态创建“ .addransient”服务?

I am calling a purchased package, which I do not have source code for. It is expecting a service pre-configured through DI. I can't change this.

I don't know all of the parameters for the service until the user logs on. User 'A' might have a different configuration than User 'B'. If no user is logged in, then the service needs to be a different way.

I can't inject it during 'Startup', as it will be configured differently for 'A' and 'B' (and 'no user')

The best place (I think) to do it is during Middleware 'Invoke', however, I can't seem to get access to IServicesCollection to perform '.AddTransient<>'

Is this even possible?

Or is there a better way to create an '.AddTransient' service dynamically?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

大姐,你呐 2025-02-20 17:16:58

如果打算在中间件调用中访问服务,则无需尝试访问serviceCollection在启动寄存器

寄存器外部使用中间件中的延期工厂委托所需的暂时服务,

//...

services.AddTransient<IService>(sp => {
    var ctx = sp.GetService<IHttpContextAccessor>().HttpContext;

    var user = //get user however you intended to get user

    //create instance of service
    return ActivatorUtilities.CreateInstance<Service>(sp, user);        
});

//...

可以通过方法注入明确注入服务

//...

public async Task InvokeAsync(HttpContext context, IService service) {
    //...
}

//...

中间件的InvokeAsync的其他参数,httpcontext由依赖项注入填充(di)。

进而注入会员时,这将解决您的瞬态服务

If intending to access the service within the middleware invoke then there is no need to try and access ServiceCollection outside of Startup

register desired transient service using deferred factory delegate

//...

services.AddTransient<IService>(sp => {
    var ctx = sp.GetService<IHttpContextAccessor>().HttpContext;

    var user = //get user however you intended to get user

    //create instance of service
    return ActivatorUtilities.CreateInstance<Service>(sp, user);        
});

//...

In the middleware the service can be explicitly injected via method injection

//...

public async Task InvokeAsync(HttpContext context, IService service) {
    //...
}

//...

Additional parameters for the middleware's InvokeAsync, after HttpContext are populated by dependency injection (DI).

This will in turn resolve your transient service when injecting into the member

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文