I may be going about this the wrong way, but I'm having trouble with my own service extension and wanting to use the strongly types options model. Could anyone help? My situation:
I have two projects: MyProject.Web (ASP.NET 5 web app) and MyProject.DataAccess (a lib to handle the data access that will be re-used in a future project).
Ideally MyProject.Web has no idea the MyProject.DataAccess is using entity framework. To that end (and to try to be idiomatic in ASP.NET 5) I've made a service extention that's something like this:
public static void AddMyProjectDataContext(this IServiceCollection services, IConfiguration configuration) { // @TODO get strongly typed options from configuration instead of magic strings var defaultConnectionOptions = configuration.GetSection("DataAccess:DefaultConnection"); var settings = new DataAccessOptions(); settings.DefaultConnection.ConntectionString = defaultConnectionOptions["ConnectionString"]; DatabaseType dbType; if (Enum.TryParse<DatabaseType>(defaultConnectionOptions["DatabaseType"], out dbType)) { settings.DefaultConnection.Type = dbType; } if (settings.DefaultConnection.Type == DatabaseType.MsSqlServer) { services.AddEntityFramework() .AddSqlServer() .AddDbContext<DataContext>(options => { options.UseSqlServer(settings.DefaultConnection.ConntectionString); }); } else { throw new NotImplementedException($"Database type ({settings.DefaultConnection.Type}) not yet implemented."); } }
As you can see I'm getting the DB settings hard-coded strings, and I'd really like to get a strongly typed options object here. I can add this line to configure the options:
services.Configure<DataAccessOptions>(Configuration);
but since I'm currently configuring the services, I don't think I'd be able to resolve a dependency from them here.
for note the extention should be used like this in the ConfigureServices method:
services.AddMyProjectDataContext(Configuration);
Am I going about this all wrong? Any help would be appreciated.