Search code examples
c#delegates

Pass delegate Action<T> explicitly to the method instead of anonymously


Let's say I'm adding a DbContext to services by dependency injection like this :

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DBConnection")));

How do I do that explicitly by providing Action delegate to the AddDbContext method with new Action<> ?

builder.Services.AddDbContext<AppDbContext>(new Action<DbContextOptionsBuilder> ??? );

What to write instead of '???'


Solution

  • You can pass the delegate in multiple ways.
    Anonymous lambda (your original)

    builder.Services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DBConnection")));
    

    Manually create an Action<>. But why anyone would want to do that?

    var action = new Action<DbContextOptionsBuilder>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DBConnection")));
    
    builder.Services.AddDbContext<AppDbContext>(action);
    

    Local or regular function

    void Configure(DbContextOptionsBuilder options)
    {
        options.UseSqlServer(builder.Configuration.GetConnectionString("DBConnection"));
    }
    
    builder.Services.AddDbContext<AppDbContext>(Configure);
    

    Action<> as a variable

    var configure = (DbContextOptionsBuilder options) => 
    {
        options.UseSqlServer(builder.Configuration.GetConnectionString("DBConnection"));
    }; 
    
    builder.Services.AddDbContext<AppDbContext>(Configure);