Reputation: 186
I'm trying to roll a high performance DAL for my ASP.NET Core API. I want to use ADO.NET and I am having difficulty designing the software architecture. I'm looking for help discussing a good approach.
My codebase will consist of three projects
I'll implement IUnitOfWork
within MyApp.Repositories
and create a concrete SqlUnitOfWork
in MyApp.API
. Startup.cs
will register IUnitOfWork
to SqlUnitOfWork
. Later on, when I get more data sources (Mongo, etc.), I can incorporate a UnitOfWorkFactory
.
Should I register each repository in Startup.cs
or simply add them as properties of IUnitOfWork
? The thinking here is I would use Dependency Injection in my Controllers, Services and Repositories, but only have to inject IUnitOfWork
.
How do I pass my connection string into the SqlUnitOfWork
? I know the connection string should stay within MyApp.API
.
Upvotes: 2
Views: 7094
Reputation: 186
The other answer is irrelevant because it is suggesting I use EF, which I want to avoid.
I implemented Dapper with a repository pattern. I did not use a unit of work because I concluded to would lead to performance loses I did not want to have.
Here is a raw prototype I implemented. https://github.com/lenardchristopher/AdoAspDotNetCoreTest
Upvotes: 3
Reputation: 2926
I believe you are working with aspnet-core thus using Entity Framework as your ORM will work in this situation.
I agree with you on registering your repositories as part of IUnitOfWork
then adding it as a service to your DI container which you will then inject in your controllers.
To answer your second question, let's assume that your SqlUnitOfWork
implementation has a constructor that receives a DbContext
instance.
In ASP.NET Core, the
DbContext
is added to the DI container and thus any other service that requires or has a dependency on DbContext in it's constructor, it will automatically be resolved by the DI container.
First remember to have your connection string defined in appsettings.json
as so.
Then now lets use that connection string to add a DbContext
object to our DI container and a little Futher reading on Configuring DbContext in EF Core
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Database")));
}
After that, registering other services to our DI container that need our context will be very easy since the container will resolve that dependency for us.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IUnitOfWork, SqlUnitOfWork>();
}
Hope this answers your questions. If not, let me know.
Upvotes: 0