Eastrall / EntityFrameworkCore.DataEncryption

A plugin for Microsoft.EntityFrameworkCore to add support of encrypted fields using built-in or custom encryption providers.
MIT License
326 stars 54 forks source link

Help for fixing bug #40

Closed planyway closed 1 year ago

planyway commented 1 year ago

Program.cs

public void ConfigureServices(IServiceCollection services)
{
 byte[] key = Encoding.ASCII.GetBytes("sample_key");
 var provider = new AesProvider(key);
services.AddDbContext<ApplicationDbContext>(builder=>{...}, provider);
}

ApplicationDbContext.cs

    public class ApplicationDbContext : DbContext
    {
        private readonly IEncryptionProvider _provider;
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IEncryptionProvider provider) : base(options)
        {
            this._provider = provider;
        }

It is surely the problem of passing provider to the constructor, that causes the error:

cannot convert from 'Microsoft.EntityFrameworkCore.DataEncryption.Providers.AesProvider' to 'Microsoft.Extensions.DependencyInjection.ServiceLifetime'

Can anyone provide me tips on how to fix that?

Eastrall commented 1 year ago

The issue is on this line:

services.AddDbContext<ApplicationDbContext>(builder => {...}, provider);

The second parameter of the AddDbContext() method is not the parameter in the constructor, but the ServiceLifeTime of the db context you want to register. Check out the docs: https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.entityframeworkservicecollectionextensions.adddbcontext?view=efcore-6.0#microsoft-extensions-dependencyinjection-entityframeworkservicecollectionextensions-adddbcontext-1(microsoft-extensions-dependencyinjection-iservicecollection-system-action((microsoft-entityframeworkcore-dbcontextoptionsbuilder))-microsoft-extensions-dependencyinjection-servicelifetime-microsoft-extensions-dependencyinjection-servicelifetime)

A possible workaround would be to register the DbContext as Scoped specify how the DbContext instance should be created:

 byte[] key = Encoding.ASCII.GetBytes("sample_key");
 var provider = new AesProvider(key);

services.AddScoped<ApplicationDbContext>(serviceProvider =>
{
    DbContextOptions<ApplicationDbContext> options = ...; // figure out how to create the db context options
    return new ApplicationDbContext(options, provider);
});