Using constructor injection when caller expects a specific constructor signature - c#

I'm new to DI in .NET C# & autofac and having problems to understand how to use DI when I can't fully control the caller side.
There are two scenarios I have problems to understand.
Scenario 1: Caller expects a default constructor (without any parameters)
How to handle this scenario when I still want to inject some Service Interfaces when the class is constructed? I was thinking of constructor chaining, but that would mean I have to know the concrete type and it works around the idea of DI. (at least I think).
public class ServiceWorker
{
IService _service;
public ServiceWorker(IService service)
{
_service = service
}
}
public class Caller
{
// No way to change this.
var serviceWorker = new ServiceWorker();
}
Scneario 2: Caller expects a specific constructor signature (e.g.
Same question here. How can I inject additional dependencies when the caller expects an exact match for the constructor signature?
I think my main issue in understanding the concept is, that I don't see how to do DI only partially when not everything is constructed by DI (caller)
public class ServiceWorker
{
IService _service;
public ServiceWorker(string name, string id, IService service)
{
_service = service
}
}
public class Caller
{
// No way to change this.
var serviceWorker = new ServiceWorker(name, id);
}
I know, this is pretty basic, but I believe I need to understand this first before moving on. Are there alternatives?

As Steven correctly points out in his comment, being restricted to a specific constructor signature is an instance of the Constrained Construction anti-pattern. Sometimes, however, that can be outside your control.
An example is the so-called 'Provider pattern', which isn't a pattern at all. In such an example, you may have to play by the rules of a third-party framework, so there isn't much you can do about it. Such frameworks should be considered unfriendly to Dependency Injection.
Consider scenario 2 in the OP, since scenario 1 is just a special case of scenario 2. If you must supply a class with a certain constructor, you could create a Facade that has the required constructor signature. This enables you to avoid polluting your well-designed classes that use Dependency Injection with the constraints imposed by the third-party framework. It could look like this:
public class ServiceWorker
{
IService _service;
public ServiceWorker(string name, string id, IService service)
{
_service = service
}
}
public class ServiceWorkerFacade
{
ServiceWorker imp;
public ServiceWorkerFacade(string name, string id)
{
imp =
new ServiceWorker(
name,
id,
new FooService(
new BarService(),
new BazService());
}
}
public class Caller
{
// No way to change this.
var serviceWorker = new ServiceWorkerFacade(name, id);
}
FooService implements IService. Just to make things interesting, I've assumed that FooService has dependencies of its own, and that those dependencies are satisfied by BarService and BazService.
As Steven suggests, then, you can (from necessity) consider the Facade's constructor the Composition Root.
If you have any opportunity to influence the design of the framework in question, you could point the developers to my guidance on designing DI-friendly frameworks.

Related

How to register and resolve multiple application life time scope objects with same interface and implementation?

There a quite a couple of similar questions but they don't seem to address this specific use case.
From my configuration (run time), I am trying to create multiple instances of a certain object (same implementation, same interface) which should have an application life time scope.
Reading the doc's I see
Scoped lifetime (as per http request)
Transient (as per resolvure)
Singleton (application lifetime)
So basically I need the singleton, but, I need multiple of them.
The .AddSingleton method and overloads doesn't seem to support any named instances.
I checked out this question, but there they are using a different (Transient) scope.
I am able to put a Name property in the interface,
Is there a way to create (and resolve) multiple similar object with the same implementation and interface with an application life time scope?
Net Core DI doesnt natively support named instances. I'm fairly sure that the implementing it the way you have detailed isnt really supported. AFAIK you have two options,
Use a different 3rd party DI provider (Ninject, SimpleInjector Autofac etc)
Use the factory pattern to create a factory object that lets you resolve the object you want and use the services.AddXXX overload methods to pass in your factory class
Additionally, this could be a duplicate of: Dependency injection resolving by name
DI requires little bit more information about how to resolve required types/instances.
You mention only one part of the problem - registration of multiple instances of same type, but what about how those instances will be consumed.
Consumption will affect on how instances should be registered.
In a case you need different instances for different cases - you can create a singleton wrapper which will contain all required instances with correspondent name
public class Wrapper
{
public IRepository Orders { get; }
public IRepository Deliveries { get; }
public IRepository Products { get; }
public Wrapper(IRepository orders, IRepository deliveries, IRepository products)
{
Orders = orders;
Deliveries = deliveries;
Products = products
}
}
IRepository will be registered as Transient, but wrapper as Singleton
services.AddTransient<IRepository, SqlRepository>();
services.AddSingleton<Wrapper>();
Whenever you need one of those instances you will inject a wrapper as a dependency and use required instance through well-named property
public class Consumer
{
private readonly Wrapper _data;
public Consumer(Wrapper data) => _data = data;
public void DoSomething()
{
var myProducts = _data.Products.GetMy();
// ...
}
}
Because DI need to know how to instantiate different instances of same class, we need to create some workaround.
Another approach is to create different types for every required instance and which will derive from original one and register them as singleton types.
public class SqlRepository
{
public void GetData() { }
}
public class Orders : SqlRepository
{
// Nothing extra
}
public class Products : SqlRepository
{
// Nothing extra
}
And registration
services.AddSingleton<SqlRepository>();
services.AddSingleton<Orders>();
services.AddSingleton<Products>();
So consumers will have required type as a dependency and only one instance for every type will be instantiated within DI.
Okay, I think the AddSingleton name is a bit inconvenient; it seems you can register multiple "singleton" instances by using .AddSingleton.
So, basically the following setup just works:
//some class
public class Foo
{
public string Name { get; set; }
}
With registration:
services.AddSingleton(new Foo { Name = "1" });
services.AddSingleton(new Foo { Name = "2" });
And resolving will result in 2 "singletons":
//note: this is just a test to resolve them: do not use this in your code.
services.BuildServiceProvider().GetServices(typeof(Foo));
The essence of this question, and answer, is that .AddSingleton doesn't seem to relate to the Singleton pattern at all.
This is what I mean:

Possible bug with dependency injection on MvvmCross

I'm currently working on a cross platform (Android and iOS) using the brilliant MVVMCross and things are going pretty great with the application and no major hassles so far.
However today I've hit one that's causing me some problems. I'm a strong believer in separation of concerns and what I'm trying to do is to register a class as a lazy singleton implementer of two different interfaces. This is my App.cs in the PCL:
public class App : Cirrious.MvvmCross.ViewModels.MvxApplication
{
public override void Initialize()
{
CreatableTypes()
.EndingWith("Service")
.AsInterfaces()
.RegisterAsLazySingleton();
RegisterAppStart<LoginViewModel>();
Mvx.LazyConstructAndRegisterSingleton<ISystemConfigProviderInitialiser, SystemConfigProvider>();
Mvx.LazyConstructAndRegisterSingleton<ISystemConfigProvider, SystemConfigProvider>();
}
}
The ISystemConfigProvider will have a number of readonly properties only and will be injected into viewmodels that need to read the system config.
The ISystemConfigProviderInitializer will be injected into the DataService (itself constructed by IoC) and has an Initialize() method that allows a poco to be passed in which sets all the properties mentioned for the ISystemConfigProvider
For completeness SystemConfigProvider is like this:
public class SystemConfigProvider: ISystemConfigProvider, ISystemConfigProviderInitialiser
{
public string Name {get;}
....
public string Z {get;}
public void Initialize(PocoObjToSetPropertiesAbove obj)
{
//set all properties
}
}
The problem I'm having is that the SystemConfigProvider class is getting created multiple times. twice, seemingly once per each interface which contradicts what I'm told by the MVVMCross wiki page about Service Location and Inversion of Control:
Technical Note> the lazy singleton implementation here is quite technical - it ensures that if a >class implements IOne and ITwo then the same instance will be returned when resolving both IOne >and ITwo.
If I do away with the ISystemConfigProviderInitialiser interface and lump the Initialize() into the ISystemConfigProvider and only LazyConstructAndRegisterSingleton the ISystemConfigProvider interface then all works fine as far as I can see but it then means that all consumers of ISystemConfigProvider can now see an Initialize() method that they shouldn't see.
I'd greatly appreciate some advice on this.
The problem here is that the Mvx IoC container treats the singleton aspect at the interface level, not the instantiated type. So it doesn't see that SystemConfigProvider is the same type and should only create one instance.
To work around this problem, there are a couple of options:
1) Simply instantiate the singleton at initialization time, then register that singleton for each interface:
var provider = Mvx.IocConstruct(SystemConfigProvider);
Mvx.RegisterSingleton<ISystemConfigProviderInitialiser>(provider);
Mvx.RegisterSingleton<ISystemConfigProvider>(provider);
2) Pass a builder Func to the registration
Mvx.RegisterSingleton(() =>
{
var provider = Mvx.IocConstruct<ISystemConfigProviderInitialiser>();
return provider;
});
Mvx.RegisterSingleton(() =>
{
var provider = Mvx.Resolve<ISystemConfigProviderInitialiser>();
if (provider == null)
{
throw new InvalidOperationException("ISystemConfigProviderInitialiser should be resolved first.");
}
return (ISystemConfigProvider)provider;
});
I'm assuming that the Initialiser should be resolved first, since there is an explicit Initialise() step, so I throw an exception if it is null.
I think Option #1 is probably better. It's simple and explicit.
Hope this helps.

WCF Service Testability and Dependency Injection

I've a WCF Service which is hosted inside MVC Application. Service interacts with several Repository (I've Code First design) to do its job. Currently I create an instance of all Repository classes inside each Service method, I think it is bad and my Service is totally coupled to Repository classes. I want to know how should I implement a nice and clean DI for WCF Service.
Thanks in Advance.
One approach you can take is to inject a repository factory in your service class and then call/get your repository from the factory.
Repository Factory:
public interface IRepositoryFactory
{
IRepositoryOne GetRepositoryOne();
IRepositoryTwo GetRepositoryTwo();
}
public class RepositoryFactory: IRepositoryFactory
{
public DataAccess.RepositoryInterfaces.IRepositoryOne GetRepositoryOne()
{
return new RepositoryOne();
}
public DataAccess.RepositoryInterfaces.IRepositoryTwo GetRepositoryTwo()
{
return new RepositoryTwo();
}
}
Service Class:
public ServiceClass: IService
{
private readonly IRepositoryFactory _repositoryFactory;
public ServiceClass(IRepositoryFactory factory)
{
_repositoryFactory = factory;
}
public IList<YourItems> GetYourItems()
{
var repository = _repositoryFactory.GetRepositoryOne();
return repository.GetItems(....);
}
}
With this approach, you'll need to register and resolve only your repository factory, not all the individual repositories. This is sort of hybrid approach, but I think it's very clean and easy to understand. Of course, you can always not use a factory and resolve your repositories in every call. I can show a sample of that too, if you'd like.
I would recommend using the Dependency Inversion Principle: Have your repositories implement a specific interface, then have your service classes take in an object (or objects) of that interface (or interfaces). Do not have it directly reference the concrete class. Then, all you'd need to do on your service class is call a method that's exposed by the interface to bring up any/all of the information that you want.
Doing so will de-couple the code from each other, since they'd both be relying on abstractions, and you'll still get the wonderful functionality that you're requesting.
Here's how you could go about doing it: Let's say your WCF service class needs RepositoryA, which implements IRepositoryA. What you would do is have a field (usually private) of type IRepositoryA on it. Then create a constructor in the service that takes in an object of type IRepositoryA, and then sets the field variable with that object being passed in. Something like what's found on this site:
For more information on the Dependency Inversion Principle, just read what Uncle Bob has to say.

Mocking out a local variable in C#

I have a C# class which instantiates on its own a NetworkCommunicator class. I'd like to mock out the NetworkCommunicator class for my unit test, and replace it with a pretty simple stub.
But the NetworkCommunicator is never passed as a parameter. It's created by the class being tested.
In Ruby, this is easy to mock out. In Java, this is why you need Dependency Injection, which is too heavy for this project. Is there a simple way to mock this out in C#, perhaps using Moq or something similar?
You mentioned that DI is too heavyweight for this project, why not try some Truck Driver's DI, thus:
public interface IDependency
{
void DoSomeStuff();
}
public class ClassUnderTest
{
private IDependency _dependency;
public ClassUnderTest(IDependency dependency)
{
_dependency = dependency;
}
public ClassUnderTest() : this(new Dependency())
{}
public void ImportantStuff()
{
_dependency.DoSomeStuff();
}
}
Using this constructor chaining technique, you can now mock the IDependency all you want, without worrying about hooking up DI or IoC.
Create a "TestClass" that inherits from your class under test.
Override that parameter with a mocked instance
Create a property on the class under test that returns the new instance
public class ClassUnderTest {
public string MethodYouAreTesting(int someInput) {
var networkCommunicator = GetNetworkCommunicator();
// Do some stuff that I might want to test
return "foo";
}
public virtual NetworkCommunicator GetNetworkCommunicator {
return new NetworkCommunicator();
}
}
[TestFixture]
public class ClassUnderTestTests {
public void GivenSomeCondition_MethodYouAreTesting_ReturnsFooString() {
var classToTest = new TestClassUnderTest();
var result = classToTest.MethodYouAreTesting(1);
Assert.That(result, Is.EqualTo("foo");
}
}
public class TestClassUnderTest : ClassUnderTest {
public override GetNetworkCommunicator {
return MockedNetworkCommunicator;
}
}
I read of this technique this in the "Art of Unit Testing" and use it frequently when refactoring to full DI doesn't make sense or when the class I'm testing isn't something I can change.
Hope this helps.
You should refactor your code and pass dependencies in. You can also use typemock as easier to use alternative to fakes in Visual Studio 2012.
There's the built-in Fakes system, pretty well described at http://msdn.microsoft.com/en-us/library/hh549175.aspx
If that is too heavy-weight for your use case you might find the PrivateObject class more useful.
I have a C# class which instantiates on its own a NetworkCommunicator class.
As you noticed, this is a show stopper in C# when you want to mock this thing out. Solution is simple, and depends on context/purpose of the instantiated class:
inject it as a dependency if it's reusable component
provide it via factory if it's something that should be created every time when demand comes in
Either way, you'll need DI (factory from the second example is naturally injected too).
In Java, this is why you need Dependency Injection, which is too heavy for this project.
Is dependency injection too heavy? DI is design pattern, it's only too heavy when used when it's not really needed. Your question clearly shows you need it. Perhaps you meant that DI container is too heavy for your project? This might be true, as depending on project's complexity, you should choose appropriate way to apply DI.
I'd like to raise one more point to be aware of when applying solution like the one proposed in Greg Smith's answer. Essentially, your API ends up with constructors:
public TestedClass() : this(new Dependency()) ...
public TestedClass(IDependency) ...
As appealing as it might be at first glance, when long-term perspective is taken into account, several issues start to emerge:
does TestedClass must have IDependency or can it do fine without it?
what default (parameterless constructor) defaults to (implementation detail-level knowledge is required to use it properly)?
it creates tightly coupled components (TestedClass assembly will possibly have to reference other assembly - Dependency's assembly, even though it might not be relevant to it anyhow)
This is an anti-pattern going under different names, e.g. Bastard Injection. Of course, some of those problems might be mitigated (like making constructor protected/internal or having default implementation in the same assembly), but the anti-pattern and its long-term consequences remain. Also note that it's by no means more simple, faster or less code than regular DI.
You'll have to ask yourself what's less heavy - applying proper DI, or going you ways around with anti-patterns and/or 3rd party frameworks (MS Fakes).

Are the unit test classes in ASP.NET MVC web project a good example?

I'm learning TDD. I know about dependency injection whereby you place the class's dependencies in the constructor's parameters and have them passed in, passing in default implementations from the default constructor eg;
public AccountController() : this( RepositoryFactory.Users())
{
}
public AccountController( IUserRepository oUserRepository)
{
m_oUserRepository = oUserRepository;
}
RepositoryFactory is a simple static class that returns the chosen implementations for the current build
But the default ASP.NET MVC web app project doesn't do this, instead the DI takes the form of public properties that are assigned in the object initializer in the test class eg; from AccountController.cs :
protected override void Initialize(RequestContext requestContext)
{
if (FormsService == null)
{ FormsService = new FormsAuthenticationService(); }
if (MembershipService == null)
{ MembershipService = new AccountMembershipService(); }
base.Initialize(requestContext);
}
And in the test class AccountControllerTest.cs :
private static AccountController GetAccountController()
{
AccountController controller = new AccountController()
{
FormsService = new MockFormsAuthenticationService(),
MembershipService = new MockMembershipService(),
Url = new UrlHelper(requestContext),
};
//snip
}
So now my AccountController class has two approaches to dependency injection. Which one should I use? Constructor injection or public properties?
Am thinking constructor injection...
Is the ASP.NET MVC use of public properties like that because you need to provide a specific way of injecting into the constructor, and the basic "create new" web app needs to be generic as a starting point?
The examples in the ASP.NET MVC are excellent demonstrations of how not to use DI.
First of all, using a default constructor as well as an overloaded constructor introduces ambiguity: does the class control its own dependencies, or does it get them from the outside? Apparently, it can't really decide.
Secondly, having a default implementation introduces tight coupling because you can't create a new instance of the default implementation without having a reference to it. However, the whole point of DI is to enable loose coupling.
Unfortunately we see this idiom a lot. In my book I call it the Bastard Injection anti-pattern; I lifted the name from one of Oren Eini/Ayende Rahien's many opinionated blog posts where he walks through a very similar example.
As a general advice I recommend using Constructor Injection in the vast majority of cases. It's easy to implement and has very strong semantics: it forces the consumer to supply an instance of the dependency, effectively stating that the dependency is mandatory.
Property Injection, on the other hand, implies that the dependency is optional, because the compiler doesn't force you to assign a value. In most cases, dependencies are not really optional, so use of this pattern should be rare.
Take a look at structuremap. You are correct...constructor injection is the preferred method of DI/IoC. Check out this article by Martin Fowler. Hope this helps you.

Categories

Resources