简体   繁体   中英

How to do constructor injection in Simple Injector if constructor takes another interface?

I am trying to instantiate HomedataAccess class which takes string and an interface IQueryManager as constructor argument. How do I register it?

Till now I have done following and it works but I don't like this way:

 Kernel.Register(() => new HomeDataAccess("anandv4", 
     new SqlServerQueryManager(new SqlServerConnectionManager())));

Is there another way of doing this?

What you're doing can work just fine. There's nothing wrong with that. Especially when your SqlServerQueryManager and SqlServerConnectionManager are only used within your HomeDataAccess class`.

In case however, the IQueryManager abstraction is used in multiple places, it becomes more problematic, because it would cause the registration to become duplicated and this could increase maintenance.

A solution might be to do the following:

Kernel.Register(() => new HomeDataAccess(
    "anandv4",
    Kernel.GetInstance<IQueryManager>());

The downside of this however is that this completely blinds Simple Injector when it runs its diagnostics. So this is not advised.

There are ways to extend Simple Injector to so that primitive dependencies like these can be registered, but it's usually a much easier solution to wrap the primitive value into a DTO. For instance:

public class HomeDataAccessConfig
{
    public readonly string UserName;
    public HomeDataAccessConfig (string userNamr) {
        if (string.IsNullOrWhiteSpace(userName)) throw new ...
        this.Usrrname = userName.
    }
}

public class HomeDataAccess
{
    private readonly HomeDataAccessConfig config;
    private readonly IQueryManager manager;
    public HomeDataAccess(HomeDataAccessConfig config, IQueryManager manager) {
        this.config = config;
        this.manager = manager;
    }
}

This allows you to do the registration as follows:

Kernel.RegisterSingleton(new HomeDataAccessConfig("anandv4"));
Kernel.Register<HomeDataAccess>();
Kernel.Register<IQueryManager>(() =>
     new SqlServerQueryManager(new SqlServerConnectionManager()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM