Entity framework 6 dynamic connections string using DI

.net-4.6 connection-string dependency-injection entity-framework-6 unit-of-work

Accepted Answer

Avoid introducing objects into the object network that are dynamic dependent on runtime data. Is the connection string still a fixed value (won't change once the programme starts) or is it subject to change with each request? (for instance, when each user gets its own connection string).

If the connection string is a constant, the answer is straightforward: Simply ask for the connection string at startup and use it endlessly, exactly as you do now.

If your connection string contains runtime data rather than a fixed value from the configuration file, it and its usingDbContext should no longer be introduced into the object graph directly. Instead, provide an abstraction that enables obtaining the accurate information.DbContext dependent on runtime data, such as the person who is logged in.

the alternative to injecting anIContext into SomeRepository and UnitOfWork introduce anIContextProvider It may be summed up as follows:

public interface IContextProvider
{
    IContext Context { get; }
}

Your DataRepositoryBase could useIContextProvider the following

public IEnumerable<TEntity> Get()
{
    return this.contextProvider.Context.Get<TEntity>();
}

public TEntity Get(object id)
{
    return this.contextProvider.Context.Find<TEntity>(id);
}

The last step is to specify a plan of action forIContextProvider that can construct and cache a connection string and load the appropriate one from the database.DbContext that connection string-based. This is just something you will be able to accomplish with the little information provided.

0
2/26/2018 3:19:06 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow