Reputation: 624
I have a .NET 5 solution that contains two projects (DataLayer and ServiceLayer). In DataLayer i have the following DbContext:
internal class ApplicationContext
: DbContext
{
public ApplicationContext(DbContextOptions<ApplicationContext> options)
: base(options)
{
}
public virtual DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);
}
}
and the following DbContextFactory:
internal sealed class ContextFactory
: IDbContextFactory<ApplicationContext>
{
public ContextFactory(DbContextOptions<ApplicationContext> options)
{
Options = options ?? throw new ArgumentNullException(nameof(options));
}
private DbContextOptions<ApplicationContext> Options { get; }
public ApplicationContext CreateDbContext()
{
return new ApplicationContext(Options);
}
}
which i use in each repository ctor:
public UserRepository(IDbContextFactory<ApplicationContext> contextFactory) { ... }
And the services initialization for DbContextFactory:
services.AddDbContextFactory<ApplicationContext>(options =>
{
options
.UseLazyLoadingProxies()
.UseSqlServer(connectionString);
});
The problem is when i try to create a migration i get the following message:
Unable to create an object of type 'ApplicationContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 for both of commands:
Add-Migration Initial
dotnet ef migrations add Initial --project DataLayer
I also have to mention that both projects are plain .NET 5 library projects and, in the service layer project, i build the ServiceCollection manually: var services = new ServiceCollection();
I searched for solutions but i didn't find any.
Thanks
Upvotes: 1
Views: 4297
Reputation: 5808
I think you can't inject anything into constructor. You should use the way described in documentation:
public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
{
public BloggingContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");
return new BloggingContext(optionsBuilder.Options);
}
}
Then you can pass any parameters through args
:
dotnet ef database update -- --environment Production --connectionstring "some_connection_string"
Upvotes: 3