How to add DbContext In Startup.cs without using Entity Framework? - c#

I am currently working on a project where I am developing a class library that later on will be uploaded as a nugget package, such that if a user creates a.NET Core application, she/he can download the nugget package and use it accordingly.
Essentially within the class library, Entity Framework, Nethereum and other packages are installed as dependencies. One of my goals is not to require users to add Entity Framework to their application (since the nugget package (, i.e. the class library I am building)) already has it installed. For that reason, there is a DbContext that accepts the database connection string in the class library and builds the options.
public class BEFDbContext: DbContext
{
public BEFDbContext(string connectionString) :
base(SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options) { }
public DbSet<ApplicationEvent> Events { get; set; }
}
Next, the user has to create another class in the application code that extends the BEFDbContext class found in the class library.
public class NewDatabaseContext: BEFDbContext
{
public NewDatabaseContext(string connectionString):base(connectionString){}
}
So far so good, however, at this point, I would like to 'initialise' the NewDatabaseContext class in the Startup.cs class. Generally, one would use Entity Framework and would add the code as such:
services.AddDbContextPool<NewDatabaseContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("defaultconnection"));
});
However, as I mentioned before One of the goals is to not require users/developers to add Entity Framework to the application (once again since we have it in the class library).
So, my question is How I can add the NewDatabaseContext class as DbCcontext in the Startup.cs without using Entity Framework?

Since you wanted the alternative response you can use Extension methods
in your library add the following code
public static class ServiceCollectionExtensions
{
public IServiceCollection AddApplicationDbContext<T>(this IServiceCollection services, IConfiguration configuration) where T : BEFDbContext
{
services.AddDbContextPool<T>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("defaultconnection"));
});
return services;
}
}
then in the startup of application you can use
public void ConfigureServices(IServiceCollection services)
{
...
services.AddApplicationDbContext<NewDatabaseContext>(Configuration);
...
}
You can have variations of this as per your need. Like accepting the connection string instead of the whole Configuration, etc.
This answer uses generics and extension methods. If you want more details then please checkout:
Generic methods: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-methods
Extension Methods: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

Related

How do I use dll of .net 5 class library that contain in its class Dependency injection?

In my Asp.net Core 5 API Project
I have a serviceLayer that the controller uses, to get data from a third layer called dataLayer.
I want to use the service layer as a DLL in different projects.
This ServiceLayer Contain dependency Injections like that :
namespace ServiceLayer
{
public class UserService : IUserService
{
IUserRepository userRepository; // (From DataLayer)
public UserService(IUserRepository repository) : base(repository)
{
this.userRepository = repository;
}
public Users GetAllPersonsById(int id)
{
return userRepository.GetById(id);
}
}
public interface IUserService : IService<Users>
{
Users GetAllPersonsById(int id);
}
How can I use the method GetAllPersonsById with the DLL ServiceLayer
can I use it because the dependency Injections
As soon as you reference the DLL / project you can use all classes the same ways as if they were in the project.
To use a class as a service:
Provide the service
Inject the service
There's a lot of documentation available, so I'll keep this short:
// provide in startup.cs
services.AddTransient<IUserService, UserService>();
// Inject where you need it
MyConstructor(IUserService userService) {}
See https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0
Provide Extension Method
If we take a look at other libs, most of them provide a method to setup the services.
Example: Entity framework core
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(...));
}
So you could:
In your lib, create an extension method for IServicesCollection that adds all services of your lib.
In the consuming project, call services.AddMyLibServices().
This could look like so:
public static class ServicesConfiguration
{
public static void AddDataLayer(this IServiceCollection services)
{
services.AddTransient<IUserService, UserService>();
// ... same for all services of your lib
}
}
Here's a tutorial with more details:
https://dotnetcoretutorials.com/2017/01/24/servicecollection-extension-pattern/
Lamar service registries
An optional and alternative approach are service registries. It's very similar to the extension methods but uses a class to do the setup. See https://jasperfx.github.io/lamar/documentation/ioc/registration/registry-dsl/
Composition Root
You may want to read about the composition root pattern, e.g. What is a composition root in the context of dependency injection?
In a simple app, your startup.cs is your composition root. In more complex apps, you could create a separate project to have a single place to configure your apps services.
Create the DLL
There are two ways to create the DLL:
As a project in your solution (so your solution has multiple projects, each will result in a separate DLL)
As a separate solution and as nuget package

How to use dotnet-ef tools with DI instanciated DbContext?

I'm using a DDD approach and added a persistence layer to my project. The layer publishes an extension method to IServiceCollection which initializes efcore. I only publish repositories instead of the DbContext itself.
IServiceCollection Extension
public static IServiceCollection AddPersistenceLayer(this IServiceCollection services, string connectionString)
{
// internal dependencies
services.AddDbContextFactory<AppDbContext>(
o => o.UseSqlServer(connectionString, p => p.EnableRetryOnFailure()));
services.AddDbContext<AppDbContext>(
o => o.UseSqlServer(connectionString, p => p.EnableRetryOnFailure()));
// public dependencies (consument of DbContext)
services.AddTransient<IBookRepository, BookRepository>();
return services;
}
DbContext
internal sealed class AppDbContext: DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
:base(options)
{
}
public DbSet<Book> Books { get; set; }
}
This works fine so far when using my app. But when I want to use the dotnet-ef tools the efcore wont be initialized because there is no startup project which calls the above extension method.
Is there a way to somehow work around this? I wish I just could pass the connectionstring from the CLI.
Migrations are also located in the persistence layer project if that matters.
What I've tried is to create a startup project which calls the extension method and then use the following command. But without success.
dotnet ef database update `
--project .\src\Persistence\Persistence.csproj `
--startup-project .\src\Persistence.Tools\Persistence.Tools.csproj `
0
I keep getting the error message
Unable to create an object of type 'AppDbContext'.
Maybe this example can help you in what you want to do:
https://andrewlock.net/using-dependency-injection-in-a-net-core-console-application/

.NET Core 2.0 Modular Dependency Injection

I am trying to build a library that has core and extensions packages like Entity Framework and its database providers.
What I am trying to do is when I register that library with dependency injection, I want to give specific implementation as a parameter.
Think EF. In order to use sql provider on EF we need to register it with SQL provider passed as option parameter like the following.
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(Configuration["ConnectionString"]);
});
I would like to build similar structure. Lets say my framework will provide film producer. It will have producer.core package for framework related classes and two extensions package called Producer.Extensions.Hollywood and Producer.Extensions.Bollywood.
If I want to use Hollywood provider, I need to install core package and Hollywood extension package. On registration it should look like
services.AddFilmProducer(options =>
{
options.UseHollywoodProducer();
});
I could not find even a keyword that will point me a direction. I tried to read entity framework's source code but it is too complicated for my case.
Is there anyone who could point me a direction?
Thanks in advance.
I'm not sure if I completely understand your requirements, but DI and extensions are an easy thing in .net core.
Let's say you want this in your Startup.cs
services.AddFilmProducer(options =>
{
options.UseHollywoodProducer();
});
To implements this, create your library and add a static extension class
public static class FilmProducerServiceExtensions
{
public static IServiceCollection AddFilmProducer(this IServiceCollection services, Action<ProducerOptions> options)
{
// Create your delegate
var producerOptions = new ProducerOptions();
options(producerOptions);
// Do additional service initialization
return services;
}
}
where your ProducerOptions implementation might look like
public class ProducerOptions
{
public void UseHollywoodProducer()
{
// Initialize hollywood
}
public void UseBollywoodProducer()
{
// Initialize bollywood
}
}
If you wish to use the passed ProducerOptions in your service, there are two ways to do it. Either use dependency injection again, or directly access the service by using service provider in your extension method
var serviceProvider = services.BuildServiceProvider()
IYourService service = sp.GetService<IYourService>();
And now you have the original Use piece of initialization working.
Hope it helps.
Edit:
To clarify. To inject your options in the service, you can use
services.Configure(ProducerOptions);
in your extension method, and pass to your service constructor via
public YourService(IOptions<ProducerOptions>)
You can then simplify or complicate your options as much as you want.
A useful link for this kind of extensions might be the CORS repository for .net core: https://github.com/aspnet/CORS
Edit after comments:
I think I've got it now. You want packages to extend and implement specific options, kind of like what serilog does with different sinks. Piece of cake.
Scrap the ProducerOptions implementation.
Lets say you have a base package with initial empty structures (BaseProducer library) and an interface
public interface IProducerOptions
{
// base method signatures
}
Your service extension now becomes
public static class FilmProducerServiceExtensions
{
public static IServiceCollection AddFilmProducer(this IServiceCollection services, Action<IProducerOptions> options)
{
// Do additional service initialization
return services;
}
}
Now you create a new package with specific "Hollywood producer" options and you want to extend the base option set
public static class HollyWoodExtensions
{
public static void UseHollywoodProducer(this IProducerOptions options)
{
// Add implementation
}
}
Create as many packages and IProducerOptions extensions as you like, and the added methods will start appearing in your Startup.cs
services.AddFilmProducer(options =>
{
options.UseHollywoodProducer();
});

Dependency injection resolving by name

How can I inject different implementation of object for a specific class?
For example, in Unity, I can define two implementations of IRepository
container.RegisterType<IRepository, TestSuiteRepositor("TestSuiteRepository");
container.RegisterType<IRepository, BaseRepository>();
and call the needed implementation
public BaselineManager([Dependency("TestSuiteRepository")]IRepository repository)
As #Tseng pointed, there is no built-in solution for named binding. However using factory method may be helpful for your case. Example should be something like below:
Create a repository resolver:
public interface IRepositoryResolver
{
IRepository GetRepositoryByName(string name);
}
public class RepositoryResolver : IRepositoryResolver
{
private readonly IServiceProvider _serviceProvider;
public RepositoryResolver(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public IRepository GetRepositoryByName(string name)
{
if(name == "TestSuiteRepository")
return _serviceProvider.GetService<TestSuiteRepositor>();
//... other condition
else
return _serviceProvider.GetService<BaseRepositor>();
}
}
Register needed services in ConfigureServices.cs
services.AddSingleton<IRepositoryResolver, RepositoryResolver>();
services.AddTransient<TestSuiteRepository>();
services.AddTransient<BaseRepository>();
Finally use it in any class:
public class BaselineManager
{
private readonly IRepository _repository;
public BaselineManager(IRepositoryResolver repositoryResolver)
{
_repository = repositoryResolver.GetRepositoryByName("TestSuiteRepository");
}
}
In addition to #adem-caglin answer I'd like to post here some reusable code I've created for name-based registrations.
UPDATE Now it's available as nuget package.
In order to register your services you'll need to add following code to your Startup class:
services.AddTransient<ServiceA>();
services.AddTransient<ServiceB>();
services.AddTransient<ServiceC>();
services.AddByName<IService>()
.Add<ServiceA>("key1")
.Add<ServiceB>("key2")
.Add<ServiceC>("key3")
.Build();
Then you can use it via IServiceByNameFactory interface:
public AccountController(IServiceByNameFactory<IService> factory) {
_service = factory.GetByName("key2");
}
Or you can use factory registration to keep the client code clean (which I prefer)
_container.AddScoped<AccountController>(s => new AccountController(s.GetByName<IService>("key2")));
Full code of the extension is in github.
You can't with the built-in ASP.NET Core IoC container.
This is by design. The built-in container is intentionally kept simple and easily extensible, so you can plug third-party containers in if you need more features.
You have to use a third-party container to do this, like Autofac (see docs).
public BaselineManager([WithKey("TestSuiteRepository")]IRepository repository)
After having read the official documentation for dependency injection, I don't think you can do it in this way.
But the question I have is: do you need these two implementations at the same time? Because if you don't, you can create multiple environments through environment variables and have specific functionality in the Startup class based on the current environment, or even create multiple Startup{EnvironmentName} classes.
When an ASP.NET Core application starts, the Startup class is used to bootstrap the application, load its configuration settings, etc. (learn more about ASP.NET startup). However, if a class exists named Startup{EnvironmentName} (for example StartupDevelopment), and the ASPNETCORE_ENVIRONMENT environment variable matches that name, then that Startup class is used instead. Thus, you could configure Startup for development, but have a separate StartupProduction that would be used when the app is run in production. Or vice versa.
I also wrote an article about injecting dependencies from a JSON file so you don't have to recompile the entire application every time you want to switch between implementations. Basically, you keep a JSON array with services like this:
"services": [
{
"serviceType": "ITest",
"implementationType": "Test",
"lifetime": "Transient"
}
]
Then you can modify the desired implementation in this file and not have to recompile or change environment variables.
Hope this helps!
First up, this is probably still a bad idea. What you're trying to achieve is a separation between how the dependencies are used and how they are defined. But you want to work with the dependency injection framework, instead of against it. Avoiding the poor discover-ability of the service locator anti-pattern. Why not use generics in a similar way to ILogger<T> / IOptions<T>?
public BaselineManager(RepositoryMapping<BaselineManager> repository){
_repository = repository.Repository;
}
public class RepositoryMapping<T>{
private IServiceProvider _provider;
private Type _implementationType;
public RepositoryMapping(IServiceProvider provider, Type implementationType){
_provider = provider;
_implementationType = implementationType;
}
public IRepository Repository => (IRepository)_provider.GetService(_implementationType);
}
public static IServiceCollection MapRepository<T,R>(this IServiceCollection services) where R : IRepository =>
services.AddTransient(p => new RepositoryMapping<T>(p, typeof(R)));
services.AddScoped<BaselineManager>();
services.MapRepository<BaselineManager, BaseRepository>();
Since .net core 3, a validation error should be raised if you have failed to define a mapping.

Entity Framework Core - Customise Scaffolding

In Entity Framework 6 we can add the T4 templates the scaffolding uses by running
Install-Package EntityFramework.CodeTemplates.CSharp
But in Entity Framework Core the scaffolding system does not appear to use T4 templates, nor does it seem like the scaffolding can be customised. It seems to be all in c# classes eg.
https://github.com/aspnet/EntityFramework/blob/a508f37cf5a0246e9b92d05429153c3d817ad5ec/src/Microsoft.EntityFrameworkCore.Tools.Core/Scaffolding/Internal/EntityTypeWriter.cs
Is there any way to customise the output from the scaffold?
There is a special, yet-to-be-documented hook to override design-time services:
class Startup
{
public static void ConfigureDesignTimeServices(IServiceCollection services)
=> services.AddSingleton<EntityTypeWriter, MyEntityTypeWriter>();
}
Then implement your custom generator.
class MyEntityTypeWriter : EntityTypeWriter
{
public EntityTypeWriter(CSharpUtilities cSharpUtilities)
: base(cSharpUtilities)
{
}
// TODO: Override with custom implementation
}
Update: See Yehuda Goldenberg's answer for another way to do this in EF Core 1.0.2+.
In .Net Core 1.1, the way to override design-time services is to implement the IDesignTimeServices interface in the startup assembly. For example:
public class MyDesignTimeServices : IDesignTimeServices
{
public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<EntityTypeWriter, MyEntityTypeWriter>();
serviceCollection.AddSingleton<DbContextWriter, MybContextWriter>();
}
}
See https://github.com/aspnet/EntityFramework/issues/5617

Categories