Reputation: 1890
I have an ASP.NET Core application, which is structured in three layers i.e.:
Until now, I have been used to developing applications in .NET Framework, however, moving to Core I notice that there are significant differences.
To start off, I used a database first approach to initialize my entity framework. Here I used the scaffolding method, and it worked just fine.
However, I noticed that app.config is no longer present in any of my libraries and that my connectionstring has been moved to a method in my source code, i.e.:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//connection stuff here
}
Compared to using EF in .net framework, I would normally utilize the connectionstring, which resides in my app.config i.e.:
public EFClass(string connString)
: base(connString)
{
This can no longer be done, and i'm forced to utilize the appsettings.json in my MVC web application, which sort of mess up the idea of loosely coupling my application.
Additionally, I've read several places that the UOW repository pattern is sort of redundant, as DbContext in .NET Core applications can be used for DI as well? Should I get rid of my UOW and just inject my DbContext directly into my repositories?
My question may be wrong, in the sense that I probably miss some major fundamentals here, but you are welcome to point me in a better direction.
Upvotes: 1
Views: 1998
Reputation: 16498
EF already implements the UoW pattern - DbSet
s are your repositories and the DbContext
is your unit of work. Filters and logic you wish to enforce on insert/update/delete of specific entities can all be configured in your DbContext
implementation (one way or another). If I don't think I can trust developers with using the DbContext
directly, I prefer to create an API.
In any case, you should be using dependency injection to provide your implementation of DbContext
to whatever class(es) should have access to it. When running your ASP.NET Core application, you register your implementation with the necessary configuration options (whatever those may be - either from your config files or elsewhere). When unit/integration testing components that utilize your DbContext
, you can construct the instance manually and pass into the constructor.
Example (from this):
public void ConfigureServices(IServiceCollection services)
{
...
// this method allows you to configure you DbContext options
services.AddDbContext<YourDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...
}
Upvotes: 4
Reputation: 126
The interface and class of your UoW class need to receive the connection string on constructor. On ConfigureServices method, inside of your Startup class, you get the connection string of appsettings.json.
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IUnitOfWork>(x => new UnitOfWork(strConnection));
}
Upvotes: 0