I am trying to understand IoC and determine whether it is a good fit for this particular scenario. I have the following code:
public class List { ... }
public class Form { ... }
public interface IService { ... }
public class ListService : IService {
public ListService(List list) { }
}
public class FormService : IService {
public FormService(Form form) { }
}
class Program {
static void Main(string[] args) {
IUnityContainer container = new UnityContainer();
container.RegisterType<IService, ListService>(new InjectionConstructor(typeof(List)));
container.RegisterType<IService, FormService>(new InjectionConstructor(typeof(Form)));
IService formService = container.Resolve<IService>(new DependencyOverride<Form>(new Form()));
IService listService = container.Resolve<IService>(new DependencyOverride<List>(new List()));
}
}
The code above obviously doesn't work because the second registration of IService overrides the first one. But the intent is to be able to resolve the right IService instance using its constructor dependency. I realized that it is not a typical IoC scenario but a hybrid factory / IoC and I want to know if unity can be wired to accommodate such scenario.
Edit for Conclusion:
The actual problem is more complex than the example above. The ServiceDefinition objects (List, Form) come from a WCF web service. From there, the system will construct the IService instance and a chain of other objects that eventually lead to a set of WPF view and view model. Some dependencies are clearly defined in the constructors, others uses interfaces as its constructor parameters.
My first approach was to use Named Registration combined with InjectionConstructor \ ResolvedParameter. But it quickly becomes quite convoluted. Per Randy's suggestion, I started looking into auto factory using Unity. Here is a related post on the technique. Here is my resulting code snippets
public class Form { }
public class FormService : IService{
[InjectionConstructor]
public FormService(Func<string, Form> func, string name):this(func(name)) { }
public FormService(Form form) { }
}
public class FormDataViewModel {
public FormDataViewModel(FormService svc) { }
}
public interface IService { }
class Program {
static Form GetForm(string name) {
//wcf call
return new Form();
}
static void Main(string[] args) {
IUnityContainer container = new UnityContainer();
container.RegisterInstance<Func<string, Form>>(GetForm);
container.RegisterType<IService, FormService>("form");
FormDataViewModel vm = container.Resolve<FormDataViewModel>(new DependencyOverride<string>("/system/form/test"));
}
}
The code above is in a sense a hybrid factory\IoC approach. Thanks goodness for the flexibility of Unity. Pure IoC would not be suitable in many of my scenarios.
With Unity the only way (out of the box) to have more than one registration associated with an interface is to use a named registration.
In your scenario as presented (the actual scenario might be more complicated) it doesn't appear that that should be an issue. I would think you would know in some way what type of service you wanted (Form vs. List).
If the scenario is more complicated then you can almost always achieve what you want with a factory (factory is mentioned in the question so it seems to fit). See Automatic Factories for some factory examples.
Basically, all applicable instances of IService could be injected into the factory and the factory could determine at runtime (and based on whatever criteria is applicable) what is the appropriate IService instance to return. You can even inject Func<IService> instead of IService to defer object creation.
Related
Here is a somewhat simplified description of the problem I'm trying to solve:
I have a service (e.g. a repository) implementing an interface that I need to inject as a dependency:
public class Service : IService { ... }
I'd like to add a decorator, for example one that add caching that also implements another interface:
public class CachingService: IService, IFlushable
{
public CachingService(IService decoratee) { ... }
public void Flush() { ... }
}
public interface IFlushable
{
public void Flush();
}
Normally, I'd just register the CachingService as an implementation of IService as as decorator, using Setup.Decorator or Setup.DecoratorWith.
But in this case I have an extra requirement related to the IFlushable interface.
There will be several different services with their own decorators, all of them implementing the both the decorated service interface and IFlushable. I need to inject all the IFlushable decorators as a dependency to be able to flush all the caches on request.
public class CacheHandler
{
public CacheHandler(IFlushable[] cache) { ... }
public void FlushAllCaches() { ... }
}
The problem is that this CacheHandler must receive the same decorator instances that were applied to the Service classes.
I have tried several solutions using RegisterMapping and tried to scope the resolution of the caches to their decorated services, but I could not make it work.
Either the I receive an error that the container cannot resolve the decorators (which makes sense) or I need to register the decorators themselves, but in the latter case the CacheHandler will receive a new set of IFlushable instances.
The more I think about the more I feel that what I'm trying to achieve here might not even by possible using a DI container. I mean maybe I'm solve this the wrong way.
My question is if my approach is valid and/or how can I get all the applied IFLushable decorator instances as a dependency.
First, I would agree with #Steven to consider inverting the control and injecting the IFlushable into the CachingService.
Second, you may realize the decorator for IService a bit differently - no need to implement it in CachingService:
[Test]
public void Answer()
{
var c = new Container();
c.Register<IService, Service>(Reuse.Singleton);
c.RegisterMany<CachingService>(Reuse.Singleton); // registers both CashingService and IFlushable with the same implementing instance
c.RegisterDelegate<CachingService, IService>(cs => cs.GetDecoratedService(), setup: Setup.Decorator);
var s = c.Resolve<IService>();
Assert.IsNotNull(s);
var cs = c.Resolve<CachingService>();
Assert.IsTrue(cs.ServiceDecorated); // check the service indeed is decorated
var f = c.Resolve<IFlushable>();
Assert.AreSame(cs, f); // check that the flushable and caching service are the same instance
}
public interface IService { }
public class Service : IService { }
// no need to implement IService for the decorator, we may use its method instead
public class CachingService : IFlushable
{
public readonly IService Service;
public bool ServiceDecorated;
public CachingService(IService service) => Service = service;
public IService GetDecoratedService()
{
ServiceDecorated = true; // do something with decorated service
return Service;
}
public void Flush() { }
}
public interface IFlushable
{
public void Flush();
}
I am using the built in .Net Core IoC container to resolve the application's dependencies. The way I have configured it is as follows with the use of Scrutor to scan my assembly:
services.Scan(s => s
.FromAssembliesOf(currentAssemblyTypesList)
.AddClasses(false)
.UsingRegistrationStrategy(RegistrationStrategy.Append)
.AsImplementedInterfaces()
.WithTransientLifetime());
Up until now I've had simple cases in which each interface is implemented by one dependency so the previous configuration works perfectly to resolve the whole dependency tree.
Now consider the following code:
public interface IService {}
public class ServiceOne : IService
{
public ServiceOne(IDependency dependency) {}
}
public class ServiceTwo : IService
{
public ServiceTwo(IDependency dependency) {}
}
public class SomeClass
{
public SomeClass(IService service) {}
public void DoSomething()
{
this.service.SomeMethod();
}
}
In this case "SomeClass" is in the middle of a dependency tree and I have two services that implement the same interface and which one should be injected into "SomeClass" will not be known until runtime. For reasons unimportant I have been asked that I should use the ActivatorUtilities class for this.
I am dealing with two scenarios for determining which IService should be instantiated:
At application startup a flag gets set that determines which service is to be used before the registration takes place (for a similar setup but NOT for the same dependency tree).
During the execution of the "DoSomething" method a decision is made for which one of the two services should be used so I'm guessing some kind of factory should be registered and injected to "SomeClass".
So the question is what do I need to change or add to the dependency registration process and how do I use the ActivatorUtilities class to accomplish these objectives?
Thank you.
It is not very clear what you are trying to achieve but I think its something like this?
services.AddTransient<IService>(sp =>
{
if (condition1 && condition2)
ActivatorUtilities.CreateInstance<ServiceOne>(sp);
else
ActivatorUtilities.CreateInstance<ServiceTwo>(sp);
});
So the trickiest part was to figure out what to do with the first scenario when the registration has already taken place and it turns out that there is a way to replace a specific definition. This can be accomplished with the following code:
Func<IServiceProvider, object> factoryMethod = sp =>
{
if (condition1 && condition2)
{
return ActivatorUtilities.CreateInstance<ServiceOne>(sp);
}
else
{
return ActivatorUtilities.CreateInstance<ServiceTwo>(sp);
}
};
services.Replace(ServiceDescriptor.Describe(typeof(IService), factoryMethod, ServiceLifetime.Transient));
This works very nicely when condition1 and condition2 are known at the time of dependency registration, in other words at application startup before any request has been made.
For the other scenario in which the conditions are not known until the application is running and a request has been made, since the built in .Net Core IoC container is not as feature rich as others like Castle or Autofac one way of doing this is to manually create a factory method object, something like the following:
public interface IServiceFactory
{
IService Get(MyObject myObject);
}
public class ServiceFactory : IServiceFactory
{
private readonly IServiceProvider sp;
public ServiceFactory(IServiceProvider sp)
{
this.sp = sp;
}
public IService Get(MyObject myObject)
{
if(myObject.SomeProperty == "whatever")
{
return ActivatorUtilities.CreateInstance<ServiceOne>(this.sp);
}
else
{
return ActivatorUtilities.CreateInstance<ServiceTwo>(this.sp);
}
}
}
The only thing to keep in mind here is that the interface can and should be defined wherever all of the rest of the applications interfaces are defined, and you DO NOT want the rest of your application to be tightly coupled to the MicrosoftExtensions.DependencyInjection package because of the use of the IServiceProvider interface so the implementation of the factory should be wherever the rest of the registration logic is defined.
I looked really hard for an example of ActivatorUtilities.CreateFactory method that would give me something like this but was unable to find one. I hope this is useful for someone.
So I have windsor set up and all of my services registered. I have a class that requires these services in the ctor, but this class isn't registered with windsor as it does not have an interface and I don't want to give it one for the sake of dependency resolution. What I'm really interested in, is having windsor resolve and inject my registered dependencies and hand me back an initialized class -- basically a factory.
The problem that I'm running into is that windsor throws because the dependent class has not been registered:
void Main()
{
var container = new WindsorContainer();
container.Register(Component
.For<ITestInterface>()
.ImplementedBy<TestImpl>()
.LifestyleTransient());
var c = container.Resolve<TestClass>(); // throws because TestClass isn't registered
c.Run();
}
public class TestClass
{
private ITestInterface _d;
public TestClass(ITestInterface d)
{
_d = d;
}
public void Run()
{
_d.Do();
}
}
public interface ITestInterface
{
void Do();
}
public class TestImpl : ITestInterface
{
public void Do()
{
Console.WriteLine("done");
}
}
What I don't want to end up doing, is something like this:
var dependency1 = container.Resolve<ITestInterface>();
var c = new TestClass(dependency1);
c.Run();
Because now we're in service locator territory. But more importantly, classes that have several dependencies...well that could get tedious.
How can I get windsor to have the desired factory effect? Or is this even possible with Windsor? I recall this being possble with Ninject.
So the popular response seems to be "Just register the component" which I really don't like at all because for such a simple use case, I could end up with a config class with hundreds of unnecessary registrations. That's kind of silly. So in the meanwhile, until I discover some built in functionality for this, I've create a cheesy extension that should land me somewhere in the middle. This extension simply takes the type, registers it for you and then tries to resolve it. That way, it's leveraging Windsor's own ctor resolution logic:
public static class WindsorExtentions
{
public static T Construct<T>(this IWindsorContainer container)
where T : class
{
if (!container.Kernel.HasComponent(typeof(T)))
container.Register(Component.For<T>());
var instance = container.Resolve<T>();
return instance;
}
}
What I would really like to do is register it, resolve it, then unregister it, but it appears that the RemoveComponent method has been removed in 3.0. This should be fine in the meanwhile. It obviously isn't all-inclusive with use cases, but when you have loads of proxy classes that have several required dependencies to be injected, I think this helps.
Usage:
var myClassWithDependencies = myContainer.Construct<MyClassWithDependencies>();
public class MyClassWithDependencies
{
public MyClassWithDependencies(
IFacebookClient facebookClient,
IGooglePlusClient googlePlusClient,
ITwitterClient twitterClient,
ISalesforceClient salesforceClient,
IReportRepository reportRepo,
IUserRepository userRepo)
{
}
}
I'm brand new to using Simple Injector although I have been using Ninject for a long time, so I am comfortable with DI in general. One thing that attracted me to want to use Simple Injector was the ease of use of Decorators.
I have been able to successfully use decorators with Simple Injector in all normal cases where the dependencies are resolved when the service is requested. However, I am having a hard time figuring out if there is a way to get my decorators applied in a case when the service must be constructed using a runtime value.
In Ninject, I could pass a ConstructorArgument to the kernel.Get<IService> request that could be inherited down the chain of N decorators all the way to the "real" implementing class. I cannot figure out a way to replicate that using Simple Injector.
I have put some very basic code below to illustrate. What I would want to do in the real world would be to pass an IMyClassFactory instance into other classes in my application. Those other classes could then use it to create IMyClass instances using the IRuntimeValue they would provide. The IMyClass instance they got from the IMyClassFactory would be decorated automatically by the registered decorators.
I know I could manually apply my decorator(s) in my IMyClassFactory or any Func<IMyClass> I could come up with, but I would like it to "just work".
I keep going around and around trying to abstract out the MyClass construction, but I can't figure out how to get it to resolve with the IRuntimeValue constructor argument and be decorated.
Am I overlooking an obvious solution?
using System;
using SimpleInjector;
using SimpleInjector.Extensions;
public class MyApp
{
[STAThread]
public static void Main()
{
var container = new Container();
container.Register<IMyClassFactory, MyClassFactory>();
container.RegisterDecorator(typeof (IMyClass), typeof (MyClassDecorator));
container.Register<Func<IRuntimeValue, IMyClass>>(
() => r => container.GetInstance<IMyClassFactory>().Create(r));
container.Register<IMyClass>(() => ?????)); // Don't know what to do
container.GetInstance<IMyClass>(); // Expect to get decorated class
}
}
public interface IRuntimeValue
{
}
public interface IMyClass
{
IRuntimeValue RuntimeValue { get; }
}
public interface IMyClassFactory
{
IMyClass Create(IRuntimeValue runtimeValue);
}
public class MyClassFactory : IMyClassFactory
{
public IMyClass Create(IRuntimeValue runtimeValue)
{
return new MyClass(runtimeValue);
}
}
public class MyClass : IMyClass
{
private readonly IRuntimeValue _runtimeValue;
public MyClass(IRuntimeValue runtimeValue)
{
_runtimeValue = runtimeValue;
}
public IRuntimeValue RuntimeValue
{
get
{
return _runtimeValue;
}
}
}
public class MyClassDecorator : IMyClass
{
private readonly IMyClass _inner;
public MyClassDecorator(IMyClass inner)
{
_inner = inner;
}
public IRuntimeValue RuntimeValue
{
get
{
return _inner.RuntimeValue;
}
}
}
Edit 1:
Ok, thanks to Steven for the great answer. It has given me a couple of ideas.
Maybe to make it a little more concrete though (although not my situation, more "classic"). Say I have an ICustomer that I create at runtime by reading a DB or deserializing from disk or something. So I guess that would be considered a "newable" to quote one of the articles Steven linked. I would like to create an instance of ICustomerViewModel so I can display and manipulate my ICustomer. My concrete CustomerViewModel class takes in an ICustomer in its constructor along with another dependency that can be resolved by the container.
So I have an ICustomerViewModelFactory that has a .Create(ICustomer customer) method defined which returns ICustomerViewModel. I could always get this working before I asked this question because in my implementation of ICustomerViewModelFactory I could do this (factory implemented in composition root):
return new CustomerViewModel(customer, container.GetInstance<IDependency>());
My issue was that I wanted my ICustomerViewModel to be decorated by the container and newing it up bypassed that. Now I know how to get around this limitation.
So I guess my follow-up question is: Is my design wrong in the first place? I really feel like the ICustomer should be passed into the constructor of CustomerViewModel because that demonstrates intent that it is required, gets validated, etc. I don't want to add it after the fact.
Simple Injector explicitly lacks support for passing on runtime values through the GetInstance method. Reason for this is that runtime values should not be used when the object graph is constructed. In other words, the constructors of your injectables should not depend on runtime values. There are several problems with doing that. First of all, your injectables might need to live much longer than those runtime values do. But perhaps more importantly, you want to be able to verify and diagnose your container's configuration and that becomes much more troublesome when you start using runtime values in the object graphs.
So in general there are two solutions for this. Either you pass on the runtime value through the method call graph or you create a 'contextual' service that can supply this runtime value when requested.
Passing on the runtime value through the call graph is especially a valid solution when you practice architectures like this and this where you pass on messages through your system or when the runtime value can be an obvious part of the service's contract. In that case it is easy to pass on the runtime value with the message or the method and this runtime value will also pass through any decorator on the way through.
In your case this would mean that the factory creates the IMyService without passing in the IRuntimeValue and your code passes this value on to the IMyService using the method(s) it specifies:
var service = _myServiceFactory.Create();
service.DoYourThing(runtimeValue);
Passing through the runtime value through the call graph however is not always a good solution. Especially when this runtime value should not be part of the contract of the message that is sent. This especially holds for contextual information use as information about the current logged in user, the current system time, etc. You don't want to pass this information through; you just want it to be available. We don't want this, because this would give an extra burden to the consumers of passing the right value every time, while they probably shouldn't even be able to change this information (take the user in who's context the request is executed for instance).
In that case you should define service that can be injected and allows retrieving this context. For instance:
public interface IUserContext {
User CurrentUser { get; }
}
public interface ITimeProvider {
DateTime Now { get; }
}
In these cases the current user and the current time aren't injected directly into a constructor, but instead these services are. The component that needs to access the current user can simply call _userContext.CurrentUser and this will be done after the object is constructed (read: not inside the constructor). Thus: in a lazy fashion.
This does mean however that the IRuntimeValue must be set somewhere before MyClass gets invoked. This probably means you need to set it inside the factory. Here's an example:
var container = new Container();
var context = new RuntimeValueContext();
container.RegisterSingle<RuntimeValueContext>(context);
container.Register<IMyClassFactory, MyClassFactory>();
container.RegisterDecorator(typeof(IMyClass), typeof(MyClassDecorator));
container.Register<IMyClass, MyClass>();
public class RuntimeValueContext {
private ThreadLocal<IRuntimeValue> _runtime;
public IRuntimeValue RuntimeValue {
get { return _runtime.Value; }
set { _runtime.Value = value; }
}
}
public class MyClassFactory : IMyClassFactory {
private readonly Container _container;
private readonly RuntimeValueContext context;
public MyClassFactory(Container container, RuntimeValueContext context) {
_container = container;
_context = context;
}
public IMyClass Create(IRuntimeValue runtimeValue) {
var instance = _container.GetInstance<IMyClass>();
_context.RuntimeValue = runtimeValue;
return instance;
}
}
public class MyClass : IMyClass {
private readonly RuntimeValueContext _context;
public MyClass(RuntimeValueContext context) {
_context = context;
}
public IRuntimeValue RuntimeValue { get { return _context.Value; } }
}
You can also let the MyClass accept the IRuntimeValue and make the following registration:
container.Register<IRuntimeValue>(() => context.Value);
But the disallows verifying the object graph, since Simple Injector will ensure that registrations never return null, but context.Value will be null by default. So another option is to do the following:
container.Register<IMyClass>(() => new MyClass(context.Value));
This allows the IMyClass registration to be verified, but will during verification still create a new MyClass instance that is injected with a null value. If you have a guard clause in the MyClass constructor, this will fail. This registration however disallows MyClass to be auto-wired by the container. Auto-wiring that class can come in handy when you've got more dependencies to inject into MyClass for instance.
I have the IRespository registered twice (with names) in the following code:
// Setup the Client Repository
IOC.Container.RegisterType<ClientEntities>(new InjectionConstructor());
IOC.Container.RegisterType<IRepository, GenericRepository>
("Client", new InjectionConstructor(typeof(ClientEntities)));
// Setup the Customer Repository
IOC.Container.RegisterType<CustomerEntities>(new InjectionConstructor());
IOC.Container.RegisterType<IRepository, GenericRepository>
("Customer", new InjectionConstructor(typeof(CustomerEntities)));
IOC.Container.RegisterType<IClientModel, ClientModel>();
IOC.Container.RegisterType<ICustomerModel, CustomerModel>();
But then when I want to resolve this (to use the IRepository) I have to do a manual resolve like this:
public ClientModel(IUnityContainer container)
{
this.dataAccess = container.Resolve<IRepository>(Client);
.....
}
What I would like to do is to have it resolved in the constructor (just like IUnityContainer). I need some way to say which named type to resolve to.
Something like this: (NOTE: Not real code)
public ClientModel([NamedDependancy("Client")] IRepository dataAccess)
{
this.dataAccess = dataAccess;
.....
}
Is there a way to make my fake code work?
You can configure dependencies with or without names in the API, attributes, or via the config file. You didn't mention XML above, so I'll assume you're using the API.
To tell the container to resolve a named dependency, you'll need to use an InjectionParameter object. For your ClientModel example, do this:
container.RegisterType<IClientModel, ClientModel>(
new InjectionConstructor( // Explicitly specify a constructor
new ResolvedParameter<IRepository>("Client") // Resolve parameter of type IRepository using name "Client"
)
);
This tells the container "When resolving ClientModel, call the constructor that takes a single IRepository parameter. When resolving that parameter, resolve with the name 'Client' in addition to the type."
If you wanted to use attributes, your example almost works, you just need to change the attribute name:
public ClientModel([Dependency("Client")] IRepository dataAccess)
{
this.dataAccess = dataAccess;
.....
}
This is a very late response but the question still shows up in Google.
So anyways, 5 years later...
I have a pretty simple approach. Usually when you need to use "named dependency" it's because you're trying to implement some kind of strategy pattern. In that case, I simply create a level of indirection between Unity and the rest of my code called the StrategyResolver to not be directly depending on Unity.
public class StrategyResolver : IStrategyResolver
{
private IUnityContainer container;
public StrategyResolver(IUnityContainer unityContainer)
{
this.container = unityContainer;
}
public T Resolve<T>(string namedStrategy)
{
return this.container.Resolve<T>(namedStrategy);
}
}
Usage:
public class SomeClass: ISomeInterface
{
private IStrategyResolver strategyResolver;
public SomeClass(IStrategyResolver stratResolver)
{
this.strategyResolver = stratResolver;
}
public void Process(SomeDto dto)
{
IActionHandler actionHanlder = this.strategyResolver.Resolve<IActionHandler>(dto.SomeProperty);
actionHanlder.Handle(dto);
}
}
Registration:
container.RegisterType<IActionHandler, ActionOne>("One");
container.RegisterType<IActionHandler, ActionTwo>("Two");
container.RegisterType<IStrategyResolver, StrategyResolver>();
container.RegisterType<ISomeInterface, SomeClass>();
Now, the nice thing about this is that I will never have to touch the StrategyResolver ever again when adding new strategies in the future.
It's very simple. Very clean and I kept the dependency on Unity to a strict minimum. The only time I would have touch the StrategyResolver is if I decide to change container technology which is very unlikely to happen.
Hope this helps!
Edit: I don't really like the accepted answer because when you use the Dependency attribute in your service's constructor you actually have a hard dependency on Unity. The Dependency attribute is part of the Unity library. At that point you might as well pass an IUnityContainer dependency everywhere.
I prefer having my service classes depend on objects that I completely own instead of having a hard dependency on an external library all over the place. Also using Dependency attribute makes the constructors signatures less clean and simple.
Furthermore, this technique allows to resolve named dependencies at runtime without having to hardcode the named dependencies in the constructor, in the application configuration file or use InjectionParameter which are all methods that require to know what named dependency to use at design time.
Edit (2016-09-19):
For those that might wonder, the container will know to pass itself when you are requesting IUnityContainer as dependency, as shown in the StrategyResolver constructor signature.
Edit (2018-10-20):
Here's another way, simply using a factory:
public class SomeStrategyFactory : ISomeStrategyFactory
{
private IStrategy _stratA;
private IStrategy _stratB;
public SomeFactory(IStrategyA stratA, IStrategyB stratB)
{
_stratA = stratA;
_stratB = stratB;
}
public IStrategy GetStrategy(string namedStrategy){
if (namedStrategy == "A") return _stratA;
if (namedStrategy == "B") return _stratB;
}
}
public interface IStrategy {
void Execute();
}
public interface IStrategyA : IStrategy {}
public interface IStrategyB : IStrategy {}
public class StrategyA : IStrategyA {
public void Execute(){}
}
public class StrategyB : IStrategyB {
public void Execute() {}
}
Usage:
public class SomeClass : ISomeClass
{
public SomeClass(ISomeStrategyFactory strategyFactory){
IStrategy strat = strategyFactory.GetStrategy("HelloStrategy");
strat.Execute();
}
}
Registration:
container.RegisterType<ISomeStrategyFactory, SomeStrategyFactory>();
container.RegisterType<IStrategyA, StrategyA>();
container.RegisterType<IStrategyB, StrategyB>();
container.RegisterType<ISomeClass, SomeClass>();
This 2nd suggestion is the same thing but using the factory design pattern.
Hope this helps!
You should be able to use ParameterOverrides
var repository = IOC.Container.Resolve<IRepository>("Client");
var clientModel = IOC.Container.Resolve<ClientModel>(new ParameterOverrides<ClientModel> { {"dataAccess", repository } } );
edit:
I'm not sure why you're passing around the UnityContainer - personally, we inject our dependencies into the constructor themselves (which is "normal" from what I've seen). But regardless, you can specify a name in your RegisterType and Resolve methods.
IOC.Container.RegisterType<IRepository, GenericRepository>("Client");
IOC.Container.Resolve<IRepository>("Client");
and it will give you the type you registered for that name.
Don't do this - just create a class ClientRepository : GenericRepository { } and utilise the Type system.