Yan Ivan Evdokimov Yan Ivan Evdokimov - 1 year ago 92
ASP.NET (C#) Question

Inject third-party class without parameterless constructor

I have created this class:

public class DbSchemaProvider : IDbSchemaProvider
private readonly IConnectionStringFactory _connectionStringFactory;
private readonly ISqlProviderNameProvider _sqlProviderNameProvider;

public DbSchemaProvider(IConnectionStringFactory connectionStringFactory, ISqlProviderNameProvider sqlProviderNameProvider)
_connectionStringFactory = connectionStringFactory;
_sqlProviderNameProvider = sqlProviderNameProvider;

public DatabaseSchema GetDbSchema(SqlConnection sqlConnection)
var connectionString = _connectionStringFactory.Create(sqlConnection.SqlConnectionType).Build(sqlConnection);
var sqlProvider = _sqlProviderNameProvider.GetProviderName(sqlConnection.SqlConnectionType);
var dbReader = new DatabaseReader(connectionString, sqlProvider, sqlConnection.Owner);

return dbReader.ReadAll();

Here I am using third-party class DatabaseReader which implements IDatabaseReader interface. I want to use it similarly to IConnectionStringFactory and ISqlProviderNameProvider - by injecting it into my class. However, I can't do it because IDatabaseReader can only accept required parameters (connectionString, sqlProvider, sqlConnection.Owner) through constructor. If I could use it with dependency injection, I would be able to unit test my class with IDatabaseReader mock. But now I don't know how to do it.

Answer Source

you could wrap the DatabaseReader itself in an interface Something like the following:

public interface IDatabaseReaderProvider{
    DatabaseReader Get(string connectionString, string sqlProviderName,  SqlConnection sqlConnection);

Then, you could inject IDatabaseReaderProvider to your DbSchemaProvider implentation and initialize the DatabaseReader in the 'Get' method

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download