6

I will use a very simple example to describe my questions. Let's say I have a class to handle database calls

public class DatabaseAccessLayer : IDatabaseAccessLayer
{
    public DatabaseAccessLayer(string uid, string password, string server)
    {
        // build connection object and so on
    }
}

Then I have a class to use it

public class MyBusinessService : IBusinessService
{
    public MyBusinessService(IDatabaseAccessLayer dal)
    {
    }
}

If I use Unity as example, I would typically wire up the IoC container this way

container.RegisterType<IDatabaseAccessLayer, DatabaseAccessLayer>(new InjectionConstructor("my_uid", "my_password", "my_server"));
container.RegisterType<IBusinessService, MyBusinessService>();

It works well if I define the parameters as known values when the IoC container is set up as application starts, for example typical web application has the values in the configuration file.

However there is one requirement that I have to pass the parameters (uid, password, server) to data access layer class for every single business service call because the values could be different each time. It looks like I have no way to use IoC container in this case.

Anybody has some comments, shall I abandon IoC container in this case or there is a better way to use IoC container?

hardywang
  • 4,864
  • 11
  • 65
  • 101
  • Will the parameter value "tuples" be randomly different for each business service call, or is there some constrained set of parameter values? If the latter, many containers (including Unity) support named dependencies, and this could be helpful here. – Mark Larter Jun 07 '16 at 18:16
  • Move the params you need into properties, and simply set them after you've gotten the instance from the IoC container. Or wrap your types in a container that has this ability, then configure the IoC to supply that. Lots of different workarounds. –  Jun 07 '16 at 18:22
  • @MarkLarter, it is your first scenario. Application has to accept the values from end users. – hardywang Jun 07 '16 at 18:50
  • @Will, can you elaborate "Or wrap your types in a container that has this ability" further? – hardywang Jun 07 '16 at 18:51
  • 1
    You basically need an abstract factory.Take a look at this: http://stackoverflow.com/a/2280289/2290059 – Yacoub Massad Jun 07 '16 at 18:54
  • Yes, the answer to your last question is at the link @YacoubMassad provided. –  Jun 07 '16 at 20:36
  • Agree with abstract factory. Your factory would dynamically create instances, based on the parameters provided. – Spock Jun 08 '16 at 04:23

0 Answers0