christopher clark
christopher clark

Reputation: 2103

How to pass IOptions through Dependency injection to another Project

I have a WebApplication targetting .net core. I have also created a Class Library targetting .net core as well.

I am creating a Users Repository following this Dapper tutorial Here

It would be nice to be able to provide the option that was injected in start up of the WebApplication into the project that will be the data access layer.

Here is the code for the Users Repository in a separate project.

class UsersRepository
    {
        private readonly MyOptions _options;
        private string connectionString;
        public UsersRepository(IOptions iopt/// insert Option here )
        {
            _options = iopt.Value;
            connectionString = _options.connString;
        }

        public IDbConnection Connection
        {
            get
            {
                return new SqlConnection(connectionString);
            }
        }

The WebApplication Project Startup looks as follows.

public class Startup
   {

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddOptions();

        services.Configure<MyOptions>(Configuration);

        services.AddMvc();
    }

and of course MyOptions is a class in the web application that has only one property connString

Upvotes: 3

Views: 3007

Answers (1)

dbattaglia
dbattaglia

Reputation: 678

One possible design is to make a new interface for your repository configuration inside your class library, and have your MyOptions type implement that interface.

For example, in your class library you can do the following:

public interface IRepositoryConfig
{
    string ConnectionString { get; }
}

public class UserRepository
{
    public UserRepository(IRepositoryConfig config)
    {
       // setup
    }
}

And in your WebAPI Startup class you can wire this up as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();

    services.Configure<MyOptions>(Configuration);

    services.AddMvc();

    services.AddScoped<IRepositoryConfig>(s =>
        s.GetService<IOptions<MyOptions>>().Value
    );

    services.AddScoped<UserRepository>();
}

Doing this will allow you to use the Asp.Net Core configuration/options framework without having to reference any Asp.Net DLLs in your class library directly.

Upvotes: 6

Related Questions