How to register Ef core db context with Castle windsor?

1.8k Views Asked by At

I " ve got a project under .net core. I want to register Ef Core Context with Castle windosr But I couldn 't find a solution to EfCore Wireup context in .net core. Thank you.

2

There are 2 best solutions below

0
amirhamini On BEST ANSWER

If you want to do this , first you need to know that you have a Context that has a DbContextOptionsBuilder parameter that has a DbContextOptionsBuilder parameter if you have added these constructor , you need to register this too , and now the code I " ve written below makes you less self - sufficient to use the OnConfiguring method.

   public static class DbContextFactoryBuilder
{
    public static IDbContext Create(string connectionString)
    {
        var result = new MyDbContext(new DbContextOptionsBuilder().UseSqlServer(connectionString).Options);
        return result;
    }
}

and code for register in castle.

container.Register(Component.For<MyDbContext>().UsingFactoryMethod(c => DbContextFactoryBuilder.Create(@"---your connection string---")));
2
Jan Muncinsky On

Another alternative is:

public class MyContext : DbContext
{
    private readonly string connectionString;

    public MyContext (string connectionString)
    {
        this.connectionString = connectionString;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(this.connectionString);
    }
}

Component.For<MyContext>().DependsOn(Property.ForKey<string>().Eq("your connection string")));