.net core generic host builder use value from one Ioc registration in a subsequent one
up vote
2
down vote
favorite
I need to register two DbContext classes in my .net core 2.1 application using the built in Ioc container. The connection details for the second context is stored in the database from the first context, so the registrations would look something like
new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services
.AddDbContext<Context1>()
.AddDbContext<Context2>( /* Connection string from context1 here */ )
.AddHostedService<MyHostedService>();
});
Is there any way for me to register Context1, get the values and then use that to register Context2?
c# .net .net-core
add a comment |
up vote
2
down vote
favorite
I need to register two DbContext classes in my .net core 2.1 application using the built in Ioc container. The connection details for the second context is stored in the database from the first context, so the registrations would look something like
new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services
.AddDbContext<Context1>()
.AddDbContext<Context2>( /* Connection string from context1 here */ )
.AddHostedService<MyHostedService>();
});
Is there any way for me to register Context1, get the values and then use that to register Context2?
c# .net .net-core
add a comment |
up vote
2
down vote
favorite
up vote
2
down vote
favorite
I need to register two DbContext classes in my .net core 2.1 application using the built in Ioc container. The connection details for the second context is stored in the database from the first context, so the registrations would look something like
new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services
.AddDbContext<Context1>()
.AddDbContext<Context2>( /* Connection string from context1 here */ )
.AddHostedService<MyHostedService>();
});
Is there any way for me to register Context1, get the values and then use that to register Context2?
c# .net .net-core
I need to register two DbContext classes in my .net core 2.1 application using the built in Ioc container. The connection details for the second context is stored in the database from the first context, so the registrations would look something like
new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services
.AddDbContext<Context1>()
.AddDbContext<Context2>( /* Connection string from context1 here */ )
.AddHostedService<MyHostedService>();
});
Is there any way for me to register Context1, get the values and then use that to register Context2?
c# .net .net-core
c# .net .net-core
asked Nov 22 at 1:15
jeevs
2,56921636
2,56921636
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
up vote
3
down vote
accepted
Use one of the overloads that will give you access to the service provider
new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services
.AddDbContext<Context1>()
.AddDbContext<Context2>((serviceProvider, options) => {
var context1 = serviceProvider.GetService<Context1>();
var connectionString = /* get Connection string from context1 here */
options.UseSqlServer(connectionString);
})
.AddHostedService<MyHostedService>();
});
Reference AddDbContext<TContext>(IServiceCollection, Action<IServiceProvider,DbContextOptionsBuilder>, ServiceLifetime, ServiceLifetime)
Thanks for the answer. I was looking at this option but wan't sure if I should do it because of this line from the docsAvoid using the service locator pattern. For example, don't invoke GetService to obtain a service instance when you can use DI instead. But I suppose there is no other option at this point.
– jeevs
Nov 22 at 1:58
@jeevs noted, they also stateLike all sets of recommendations, you may encounter situations where ignoring a recommendation is required. Exceptions are rare—mostly special cases within the framework itself.
– Nkosi
Nov 22 at 2:01
@jeevs short of directly injecting the first context into the second, (which would also act like a factory), this is a special case as you have one context dependent on something that it can only get from another context.
– Nkosi
Nov 22 at 2:02
Yep, agreed. Thanks again.
– jeevs
Nov 22 at 2:23
Any idea how theAddDbContextmethod obtains a reference to the one-and-onlyIServiceProviderinstance that is eventually built? Or does it cheat and create its own provider from theIServiceCollection? The former would be impressive, the latter disappointing.
– Timo
Nov 26 at 15:04
|
show 2 more comments
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53422628%2fnet-core-generic-host-builder-use-value-from-one-ioc-registration-in-a-subseque%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
3
down vote
accepted
Use one of the overloads that will give you access to the service provider
new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services
.AddDbContext<Context1>()
.AddDbContext<Context2>((serviceProvider, options) => {
var context1 = serviceProvider.GetService<Context1>();
var connectionString = /* get Connection string from context1 here */
options.UseSqlServer(connectionString);
})
.AddHostedService<MyHostedService>();
});
Reference AddDbContext<TContext>(IServiceCollection, Action<IServiceProvider,DbContextOptionsBuilder>, ServiceLifetime, ServiceLifetime)
Thanks for the answer. I was looking at this option but wan't sure if I should do it because of this line from the docsAvoid using the service locator pattern. For example, don't invoke GetService to obtain a service instance when you can use DI instead. But I suppose there is no other option at this point.
– jeevs
Nov 22 at 1:58
@jeevs noted, they also stateLike all sets of recommendations, you may encounter situations where ignoring a recommendation is required. Exceptions are rare—mostly special cases within the framework itself.
– Nkosi
Nov 22 at 2:01
@jeevs short of directly injecting the first context into the second, (which would also act like a factory), this is a special case as you have one context dependent on something that it can only get from another context.
– Nkosi
Nov 22 at 2:02
Yep, agreed. Thanks again.
– jeevs
Nov 22 at 2:23
Any idea how theAddDbContextmethod obtains a reference to the one-and-onlyIServiceProviderinstance that is eventually built? Or does it cheat and create its own provider from theIServiceCollection? The former would be impressive, the latter disappointing.
– Timo
Nov 26 at 15:04
|
show 2 more comments
up vote
3
down vote
accepted
Use one of the overloads that will give you access to the service provider
new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services
.AddDbContext<Context1>()
.AddDbContext<Context2>((serviceProvider, options) => {
var context1 = serviceProvider.GetService<Context1>();
var connectionString = /* get Connection string from context1 here */
options.UseSqlServer(connectionString);
})
.AddHostedService<MyHostedService>();
});
Reference AddDbContext<TContext>(IServiceCollection, Action<IServiceProvider,DbContextOptionsBuilder>, ServiceLifetime, ServiceLifetime)
Thanks for the answer. I was looking at this option but wan't sure if I should do it because of this line from the docsAvoid using the service locator pattern. For example, don't invoke GetService to obtain a service instance when you can use DI instead. But I suppose there is no other option at this point.
– jeevs
Nov 22 at 1:58
@jeevs noted, they also stateLike all sets of recommendations, you may encounter situations where ignoring a recommendation is required. Exceptions are rare—mostly special cases within the framework itself.
– Nkosi
Nov 22 at 2:01
@jeevs short of directly injecting the first context into the second, (which would also act like a factory), this is a special case as you have one context dependent on something that it can only get from another context.
– Nkosi
Nov 22 at 2:02
Yep, agreed. Thanks again.
– jeevs
Nov 22 at 2:23
Any idea how theAddDbContextmethod obtains a reference to the one-and-onlyIServiceProviderinstance that is eventually built? Or does it cheat and create its own provider from theIServiceCollection? The former would be impressive, the latter disappointing.
– Timo
Nov 26 at 15:04
|
show 2 more comments
up vote
3
down vote
accepted
up vote
3
down vote
accepted
Use one of the overloads that will give you access to the service provider
new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services
.AddDbContext<Context1>()
.AddDbContext<Context2>((serviceProvider, options) => {
var context1 = serviceProvider.GetService<Context1>();
var connectionString = /* get Connection string from context1 here */
options.UseSqlServer(connectionString);
})
.AddHostedService<MyHostedService>();
});
Reference AddDbContext<TContext>(IServiceCollection, Action<IServiceProvider,DbContextOptionsBuilder>, ServiceLifetime, ServiceLifetime)
Use one of the overloads that will give you access to the service provider
new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services
.AddDbContext<Context1>()
.AddDbContext<Context2>((serviceProvider, options) => {
var context1 = serviceProvider.GetService<Context1>();
var connectionString = /* get Connection string from context1 here */
options.UseSqlServer(connectionString);
})
.AddHostedService<MyHostedService>();
});
Reference AddDbContext<TContext>(IServiceCollection, Action<IServiceProvider,DbContextOptionsBuilder>, ServiceLifetime, ServiceLifetime)
answered Nov 22 at 1:25
Nkosi
108k16113182
108k16113182
Thanks for the answer. I was looking at this option but wan't sure if I should do it because of this line from the docsAvoid using the service locator pattern. For example, don't invoke GetService to obtain a service instance when you can use DI instead. But I suppose there is no other option at this point.
– jeevs
Nov 22 at 1:58
@jeevs noted, they also stateLike all sets of recommendations, you may encounter situations where ignoring a recommendation is required. Exceptions are rare—mostly special cases within the framework itself.
– Nkosi
Nov 22 at 2:01
@jeevs short of directly injecting the first context into the second, (which would also act like a factory), this is a special case as you have one context dependent on something that it can only get from another context.
– Nkosi
Nov 22 at 2:02
Yep, agreed. Thanks again.
– jeevs
Nov 22 at 2:23
Any idea how theAddDbContextmethod obtains a reference to the one-and-onlyIServiceProviderinstance that is eventually built? Or does it cheat and create its own provider from theIServiceCollection? The former would be impressive, the latter disappointing.
– Timo
Nov 26 at 15:04
|
show 2 more comments
Thanks for the answer. I was looking at this option but wan't sure if I should do it because of this line from the docsAvoid using the service locator pattern. For example, don't invoke GetService to obtain a service instance when you can use DI instead. But I suppose there is no other option at this point.
– jeevs
Nov 22 at 1:58
@jeevs noted, they also stateLike all sets of recommendations, you may encounter situations where ignoring a recommendation is required. Exceptions are rare—mostly special cases within the framework itself.
– Nkosi
Nov 22 at 2:01
@jeevs short of directly injecting the first context into the second, (which would also act like a factory), this is a special case as you have one context dependent on something that it can only get from another context.
– Nkosi
Nov 22 at 2:02
Yep, agreed. Thanks again.
– jeevs
Nov 22 at 2:23
Any idea how theAddDbContextmethod obtains a reference to the one-and-onlyIServiceProviderinstance that is eventually built? Or does it cheat and create its own provider from theIServiceCollection? The former would be impressive, the latter disappointing.
– Timo
Nov 26 at 15:04
Thanks for the answer. I was looking at this option but wan't sure if I should do it because of this line from the docs
Avoid using the service locator pattern. For example, don't invoke GetService to obtain a service instance when you can use DI instead. But I suppose there is no other option at this point.– jeevs
Nov 22 at 1:58
Thanks for the answer. I was looking at this option but wan't sure if I should do it because of this line from the docs
Avoid using the service locator pattern. For example, don't invoke GetService to obtain a service instance when you can use DI instead. But I suppose there is no other option at this point.– jeevs
Nov 22 at 1:58
@jeevs noted, they also state
Like all sets of recommendations, you may encounter situations where ignoring a recommendation is required. Exceptions are rare—mostly special cases within the framework itself.– Nkosi
Nov 22 at 2:01
@jeevs noted, they also state
Like all sets of recommendations, you may encounter situations where ignoring a recommendation is required. Exceptions are rare—mostly special cases within the framework itself.– Nkosi
Nov 22 at 2:01
@jeevs short of directly injecting the first context into the second, (which would also act like a factory), this is a special case as you have one context dependent on something that it can only get from another context.
– Nkosi
Nov 22 at 2:02
@jeevs short of directly injecting the first context into the second, (which would also act like a factory), this is a special case as you have one context dependent on something that it can only get from another context.
– Nkosi
Nov 22 at 2:02
Yep, agreed. Thanks again.
– jeevs
Nov 22 at 2:23
Yep, agreed. Thanks again.
– jeevs
Nov 22 at 2:23
Any idea how the
AddDbContext method obtains a reference to the one-and-only IServiceProvider instance that is eventually built? Or does it cheat and create its own provider from the IServiceCollection? The former would be impressive, the latter disappointing.– Timo
Nov 26 at 15:04
Any idea how the
AddDbContext method obtains a reference to the one-and-only IServiceProvider instance that is eventually built? Or does it cheat and create its own provider from the IServiceCollection? The former would be impressive, the latter disappointing.– Timo
Nov 26 at 15:04
|
show 2 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53422628%2fnet-core-generic-host-builder-use-value-from-one-ioc-registration-in-a-subseque%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown