ubaid
ubaid

Reputation: 148

Design pattern for implementing IOC with implementations that take different initialization configuration

Here is a design that I am looking to build:

  1. An interface IStorage that contains contract for storage of data. This would contain methods like Save, Retrieve, etc.
  2. One implementation of the interface that stores data in file system.
  3. Another implementation of the interface that stores the data in some database.

Now I want to implement IOC on this using something like Castle so that I can plug in any behavior that I want. But the problem is that the configuration parameters for initialization of both the implementations would be different. For example, the file system implementation will take directory path, credentials etc. As configuration and the database one would maybe take connection string.

So if I create a common configuration interface, lets say IConfiguration, that could be used in both the implementations(and in the interface), it would contain properties that are irrelevant to one or the other implementations.

So how should I design this? Is my approach correct for designing such a system and if not what are the better ways or patterns to do so?

Upvotes: 1

Views: 100

Answers (2)

Mark Seemann
Mark Seemann

Reputation: 233307

Implementation-specific configuration goes in the constructors of the concrete classes, and are not part of the interface:

public class FileStorage : IStorage
{
    private readonly DirectoryInfo directory;
    private readonly Credentials credentials;

    public FileStorage(DirectoryInfo directory, Credentials credentials)
    {
        this.directory = directory;
        this.credentials = credentials;
    }

    // implement Save, Retrieve, etc. methods here...
}

public class SqlStorage : IStorage
{
    private readonly string connectionString;

    public SqlStorage(string connectionString)
    {
        this.connectionString = connectionString;
    }

    // implement Save, Retrieve, etc. methods here...
}

Upvotes: 1

Wiktor Zychla
Wiktor Zychla

Reputation: 48279

You seem to assume that having one configuration interface would mean that you have just one configuration section for it.

But this would be so only if you had just one implementation!

In other words, different implementations are allowed to have their own specific configuration sections.

Upvotes: 1

Related Questions