Sql DB migation failure due to not able to resolve dbContext type winform application

I am doing a Winform application in .NET 8. In my solution, I am having two projects at the moment. One is UI, the other one is database migration project, which is delicated to store entities, migrations and so on.

in my program.cs file

internal static class Program

{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        string conn = "Data Source=(local);Initial Catalog=DcCentral;Integrated Security=True";
        var serviceProvider = new ServiceCollection().AddDbContext<DcCentralDbContext>(options => options.UseSqlServer(conn)).BuildServiceProvider();

        using (var context = serviceProvider.GetService<DcCentralDbContext>())
        {
            context.Database.EnsureCreated();
        }
            
        Application.Run(new MainForm());

    }

        
    }

}

the following code is my database migration db context:

public class DcCentralDbContext : DbContext
{
    private readonly string _connectionString;
    public DbSet<DataEntry> DataEntries { get; set; }
 
    public DcCentralDbContext(DbContextOptions<DcCentralDbContext> options): base(options) 
    {
            
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(_connectionString);
    }
}
  • I tested my connection string, which is fine.
  • The database project is referenced by winform project
    I used EF migrations tool to do the migration and my command is

dotnet ef migrations add test –project ./DC.Database –context
DcCentralDbContext –startup-project ./DC.UI –verbose

The build was success, but it hit an error say the dbcontext is not be able to be resolved.

C# --framework net8.0-windows --nullable --working-dir C:\Users\Admin\Documents\DachCentral --verbose
Using assembly 'DC.Database'.
Using startup assembly 'Dc.WorkStation.WinFormUI'.
Using application base 'C:\Users\Admin\Documents\DachCentral\DcLabTool\bin\Debug\net8.0-windows'.
Using working directory 'C:\Users\Admin\Documents\DachCentral\DcLabTool'.
Using root namespace 'DC.Database'.
Using project directory 'C:\Users\Admin\Documents\DachCentral\DC.Database\'.
Remaining arguments: .
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider in assembly 'Dc.WorkStation.WinFormUI'...
Finding Microsoft.Extensions.Hosting service provider...
No static method 'CreateHostBuilder(string[])' was found on class 'Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'DcCentralDbContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create a 'DbContext' of type 'DcCentralDbContext'. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[DC.Database.DbContexts.DcCentralDbContext]' while attempting to activate 'DC.Database.DbContexts.DcCentralDbContext'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
 ---> System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[DC.Database.DbContexts.DcCentralDbContext]' while attempting to activate 'DC.Database.DbContexts.DcCentralDbContext'.
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass20_5.<FindContextTypes>b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create a 'DbContext' of type 'DcCentralDbContext'. The exception 'Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[DC.Database.DbContexts.DcCentralDbContext]' while attempting to activate 'DC.Database.DbContexts.DcCentralDbContext'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

I am very confused about this error, in my dbcontext class, the options was passed in with a DcCentralDbContext.

Is there anything I missed which is delicated for Winform applicaiton. Thanks in advance

  • This question is asked here very often. Have you looked at the link for three solutions?

    – 

  • Yeah, I have. I tried and it does not work. The solution in the links work for ASP.NET project fine, but not winform

    – 

  • The solutions in the link work in any type of project. You must implement one of three ways: either a host, or a constructor without parameters, or a factory.

    – 

  • delicated ? Did you perhaps mean dedicated ?

    – 

Leave a Comment