How do I inject a multiple interface service into a class? - c#

Following this example I can create a service with multiple interfaces
builder.Services.AddSingleton<SweetAlert>();
builder.Services.AddSingleton<ISweetAlert, SweetAlert>(implementationFactory: x =>
x.GetRequiredService<SweetAlert>());
builder.Services.AddSingleton<ISweetAlert2, SweetAlert>(x =>
x.GetRequiredService<SweetAlert>());
builder.Services.AddAutoMapper(typeof(Program));
But then how do I inject it into the class? Either I don't get it or the author doesn't address the situation.
Because it has two interfaces the usual constructor injection won't work.

Assuming no other problems in the code, injecting two (or more) dependencies to a component should be as simple as adding multiple parameters to its constructor
public class Foobarizer
{
private readonly ISweetAlert alert1;
private readonly ISweetAlert2 alert2;
public Foobarizer(
ISweetAlert alert1,
ISweetAlert2 alert2
)
{
this.alert1 = alert1;
this.alert2 = alert2;
}
public void DoTheTrick()
{
this.alert1.Foo();
this.alert2.Bar();
}
}
For this, it doesn't matter where the instances of ISweetAlert and ISweetAlert2 come from. For this Foobarizer with 2 dependencies, they could be separate objects, they could be the same object, no difference. At least from Foobarizer's point of view.
For the container, there is a small difference, and that's why the article you cited provided a section on this special case of sharing a single singleton under two interfaces. But it doesn't impact (or: shouldn't impact but sometimes does (*)) how the Foobarizer looks like.
(*) that somewhat depends on the DI/IoCC library, but you probably use aspnet6's built-in one, so, it doesn't.

Related

Inject a service with parameters in Asp.Net Core, where one parameter is a nested service and the other parameters are usual variables

How to pass several parameters into a constructor, where one of the parameters is a nested service, and the second parameter is an ordinary variable. I have seen articles explaining how to do this with a nested service. It is recommended to do it with a Factory. But I have one more parameter. Below is an example of what my service looks like.
class RootService : IRootService
{
private readonly ILogger<RootService> _logger;
private bool _myParam;
public RootService(ILogger<RootService> logger, bool myParam) =>
(_logger, _myParam) = (logger, myParam);
}
Below is an example of what dependency registration looks like.
serviceCollection.AddSingleton(<IRootService, RootService>( _ => new RootService(myParam)));
ILogger is injected automatically by the framework behind the scenes.
This is one of the scenarios that the options pattern was created for.
Create your strongly-typed options class:
public class RootServiceOptions
{
public bool MyParam { get; set; }
}
Change your constructor to accept an instance of IOptions<RootServiceOptions>:
class RootService : IRootService
{
private readonly ILogger<RootService> _logger;
private readonly bool _myParam;
public RootService(ILogger<RootService> logger, IOptions<RootServiceOptions> options) =>
(_logger, _myParam) = (logger, options.Value.MyParam);
}
Create and populate RootServiceOptions in Startup.cs/ConfigureServices using the Configure extension method:
// o is of type RootServiceOptions and is the instance that will be injected
services.Configure<RootServiceOptions>(o => o.MyParam = <boolean value from somewhere>);
Profit.
You should listen to the articles you've read that mention factories as that's definitely good advice.
The .net core container has good support for inline factories at your composition root for weird scenarios. I agree with Ihor in part, although IOptions<T> is if something is being loaded from a config file.
Really, it depends on your intended use cases. After all, your code should be SOLID and your classes should be honest about their dependencies via constructor definitions.
A nested dependency sounds a bit odd, as things like that should be taken care of by your container. The container can then make your services that need services! That's its job and If this isn't possible, you probably need to rethink your design to be less coupled and more abstract. Where everything has a single responsibility and is injectable as a service. Think SOLID.
If any of your constructor dependencies require primitive types or take strings, then that is something you should register within a factory at your composition root.

Why using the factory pattern when a simple dependecy injection is enough

Im looking to this example to understand the use of factory pattern.
I'm really amator in this field so excuse my silly question.
My problem is that i don't see the use of the factory pattern which return us the interface that we can inject it directly when we need to use it.
In the example above I would do something like this:
public class Program
{
// register the interfaces with DI container in a separate config class (Unity in this case)
private readonly IShippingStrategy _shippingStrategy;
public Program(IShippingStrategy shippingStrategy)
{
_shippingStrategy= shippingStrategy;
}
public int DoTheWork(Order order)
{
// assign properties just as an example
order.ShippingMethod = "Fedex";
order.OrderTotal = 90;
order.OrderWeight = 12;
order.OrderZipCode = 98109;
int shippingCost = _shippingStrategy.CalculateShippingCost(order);
return shippingCost;
}
}
Instead of injecting the factory :
public class Program
{
// register the interfaces with DI container in a separate config class (Unity in this case)
private readonly IShippingStrategyFactory _shippingStrategyFactory;
public Program(IShippingStrategyFactory shippingStrategyFactory)
{
_shippingStrategyFactory = shippingStrategyFactory;
}
public int DoTheWork(Order order)
{
// assign properties just as an example
order.ShippingMethod = "Fedex";
order.OrderTotal = 90;
order.OrderWeight = 12;
order.OrderZipCode = 98109;
IShippingStrategy shippingStrategy = _shippingStrategyFactory.GetShippingStrategy(order);
int shippingCost = shippingStrategy.CalculateShippingCost(order);
return shippingCost;
}
}
Why taking the bruden to create a factory (thus adding an extra layer) when we can inject the interface directly to wherever we need to use it ?
I think you don't want just another article about the factory pattern but a short comprehensive answer.
So, I'd like to focus on two things.
More flexibility
Most commonly, you'd set up your composition root where you basically say ...
"if anyone wants IAnyService, he should get MyAnyServiceImplementation".
This is fixed for your application. Once set up, your dependency injection container will serve the class instances you registered but you should not try to re-configure that container again. That's perfect for startup flexibility like registering implementation for data access components by the application's configuration, for example. Say ...
"if anyone wants IUserRepository, he should get MsSqlUserRepository because we are working with MSSQL server".
Of course, having that "immutable" composition root limits the possibilities to choose an implementation in runtime depending of the applications' state.
Instead you can inject a class which decides on a current state which service implementation to choose. Data validation is a typical scenario for that pattern because there might be different rules for different entities on your system. The buzzword here is "rule pattern" or "strategy pattern".
Lifetime control
Think of a long-living class instance like a view (user interface) or any class attached to it (like a viewmodel or a controller). As long as a user is active on a view, the class is alive. By injecting a class instance to the constructor of the view controller, for example, you hold an active instance of it as long as the view lives.
Let's say you want to use a data repository to connect to a database for example. These database access calls should be short and you do not want to keep connections open for a long time. With a repository factory, you could control the lifetime very precisely and make sure that the class is removed after it has been used:
using (var repository = new _factory.CreateRepository(...))
{
return repository.GetAnything();
}
With this, a very lightweight class - the factory - gets injected and lives as long as the view controller lives. The heavy classes - the connection things - should not live long and are just created when needed.
In fact, chances are that the repository is not instantiated at all if there's no requirement to load the data (because of an upfront cache hit, for example). If you would have injected the repository directly, you'd guarantee that one long living instance lives in memory in every case.
If you check the code for the factory you can see that depending on the ShippingMethod of the order a different implementation of the IShippingStrategy is returned by the factory. Since the ShippingMethod is only known once DoTheWork has been called it's impossible to inject the right implementation when the class is constructed (and the same class might even need different implementations for different orders).

Using optional singletons in OOP?

I'm writing a PCL in .NET and I have a wrapper class around HttpClient that loads an HtmlAgilityPack.HtmlDocument from a URI in multiple different methods. It is stateless, so I would really like to make it static, since in my opinion instantiating something with new gives the impression that it contains state. However, I have a couple of interfaces that I want it to inherit from, so it can't be static. This is where I thought of making it a singleton. Here are a few snippets from the code:
public class ConcurrentClient : IAsyncClient<HtmlDocument>
{
private static readonly ConcurrentClient _Instance = new ConcurrentClient();
private ConcurrentClient() { }
public static ConcurrentClient Instance
{
get { return _Instance; }
}
public HtmlDocument LoadUri(string uri)
{
return LoadUriAsync(uri).Result;
}
// ...
public async Task<HtmlDocument> LoadUriAsync(string uri,
Encoding e, NetworkCredential creds, Action<HtmlDocument> prehandler)
{
// ...
}
}
I'm wondering, though, if I should change the beginning parts to this:
private static readonly ConcurrentClient _SharedInstance = new ConcurrentClient();
public static ConcurrentClient SharedInstance
{
get { return _SharedInstance; }
}
The reason for this is I'm not that sure about using the Singleton pattern, mainly because I've rarely seen it in use in other libraries (maybe WinRT's Application.Current?), and I think it would encourage users of my PCL to write coupled code, since it's much easier to just call ConcurrentClient.Instance everywhere than it is to pass it in as a parameter.
However, I do want to encourage the use of a shared instance because excluding the reasons above, there's very little point in calling new ConcurrentClient() because all it does is create more memory overhead. Also, I can't think of a better way to implement inheritance with methods that don't really rely on state.
Your Singleton already implements 2 interfaces. The question really is, where are the dependencies to this Singleton and why are they there ?
If the answer is that these dependencies are there because they need to get to the implementation of those interfaces then I would say that this is wrong.
The whole point of doing a SOLID design is to have dependencies towards interfaces and not towards any concrete implementation. So anyone who needs any of these 2 interfaces should be given those interfaces via dependency injection. So that means that the interfaces would be passed by their constructor or via an extra parameter in a method call, a strategy pattern, ...
Also see this : http://blogs.msdn.com/b/scottdensmore/archive/2004/05/25/140827.aspx
There can be a reason to make a singleton, but based on your explanation this is not that clear.
Investigate more of your time in using dependency injection. If you have that under control move one step further and investigate on how you can use an inversion of control container.
Also, it's easy to forget DI and passing around the object as a parameter when you can just access it by Singleton.Instance.
You are forgetting about unit testing. If you pass interfaces to your class constructors you can easily mock those interfaces and test your class functionality. With your singleton in place, your classes really need that singleton. Unit testing will be harder.
Of course Instance is easy to access, it's a global and since people revert back to old habits of programming towards objects all the time, that is why it is so popular.

Benefit of IoC over my Factory Singleton

There seems to be a stigma on SO regarding use of Singletons. I've never personally bought into it but for the sake of open mindedness I'm attempting to give IoC concepts a try as an alternative because I'm frankly bored with my everyday work and would like to try something different. Forgive me if my interpretation of IoC concepts are incorrect or misguided.
Here's the situation: I'm building a simple HttpListener based web server in a windows service that utilizes a plug-in model to determine how a request should be handled based on the URL requested (just like everyone else that asks about HttpListener). My approach to discovering the plug-ins is to query a configured directory for assemblies decorated with a HttpModuleAssemblyAttribute. These assemblies can contain 0 or more IHttpModule children who in addition are decorated with a HttpModuleAttribute used to specify the module's name, version, human readable description and various other information. Something like:
[HttpModule(/*Some property values that matter */)]
public class SimpleHttpModule : IHttpModule
{
public void Execute(HttpListenerContext context)
{
/* Do Something Special */
}
}
When an HttpModule is discovered I would typically add it to a Dictionary<string, Type> object who's sole purpose is to keep track of which modules we know about. This dictionary would typically live in my variety of a Singleton which takes on the persona of an ACE style Singleton (a legacy from my C++ days where I learned about Singletons).
Now what I am trying to implement is something similar using (my understanding of) general IoC concepts. Basically what I have is an AppService collection where IAppService is defined as:
public interface IAppService : IDisposable
{
void Initialize();
}
And my plug-in AppService would look something like:
[AppService("Plugins")]
internal class PluginAppService : IAppService, IDictionary<string, Type>
{
/* Common IDictionary Implementation consisting of something like: */
internal Type Item(string modName)
{
Type modType;
if (!this.TryGetValue(modName, out modType)
return null;
return modType;
}
internal void Initialize()
{
// Find internal and external plug-ins and add them to myself
}
// IDisposable clean up method that attempts to dispose all known plug-ins
}
Then during service OnStart I instantiate an instance of AppServices which is locally known but passed to the constructor of all instantiated plug-ins:
public class AppServices : IDisposable, IDictionary<string, IAppService>
{
/* Simple implementation of IDictionary */
public void Initialization()
{
// Find internal IAppService implementations, instantiate them (passing this as a constructor parameter), initialize them and add them to this.
// Somewhere in there would be something like
Add(appSvcName, appSvc);
}
}
Our once single method implementation becomes an abstract implementation + a constructor on the child:
[HttpModule(/*Some property values that matter */)]
public abstract class HttpModule : IHttpModule
{
protected AppServices appServices = null;
public HttpModule(AppServices services)
{
appServices = services;
}
public abstract void Execute(HttpListenerContext context);
}
[HttpModule(/*Some property values that matter */)]
public class SimpleHttpModule : HttpModule
{
public SimpleHttpModule(AppServices services) : base(services) { }
public override void Execute(HttpListenerContext context)
{
/* Do Something Special */
}
}
And any access to commonly used application services becomes:
var plugType = appServices["Plugins"][plugName];
rather than:
var plugType = PluginManager.Instance[plugName];
Am I missing some basic IoC concept here that would simplify this all or is there really a benefit to all of this additional code? In my world, Singletons are simple creatures that allow code throughout a program to access needed (relatively static) information (in this case types).
To pose the questions more explicitly:
Is this a valid implementation of a Factory Singleton translated to IoC/DI concepts?
If it is, where is the payback/benefit for the additional code required and imposition of a seemingly more clunky API?
IoC is a generic term. Dependency Injection is the more preferred term these days.
Dependency Injection really shines in several circumstances. First, it defines a more testable architecture than solutions that have hard-coded instantiations of dependencies. Singletons are difficult to unit test because they are static, and static data cannot be "unloaded".
Second, Dependency Injection not only instantiates the type you want, but all dependant types. Thus, if class A needs class B, and class B needs class C and D, then a good DI framework will automatically create all dependencies, and control their lifetimes (for instance, making them live for the lifetime of a single web request).
DI Containers can be though of as generic factories that can instantiate any kind of object (so long as it's properly configured and meets the requirments of the DI framework). So you don't have to write a custom factory.
Like with any generic solution, it's designed to give 90% of the use cases what they need. Sure, you could create a hand crafted custom linked list data structure every time you need a collection, but 90=% of the time a generic one will work just fine. The same is true of DI and Custom Factories.
IoC becomes more interesting when you get round to writing unit tests. Sorry to answer a question with more questions, but... What would the unit tests look like for both of your implementations? Would you be able to unit test classes that used the PluginManager without looking up assemblies from disk?
EDIT
Just because you can achieve the same functionality with singletons doesn't mean it's as easy to maintain. By using IoC (at least this style with constructors) you're explicitly stating the dependencies an object has. By using singletons that information is hidden within the class. It also makes it harder to replace those dependencies with alternate implementations.
So, with a singleton PluginManager it would difficult to test your HTTP server with mock plugins, rather it looking them up from some location on disk. With the IoC version, you could pass around an alternate version of the IAppService that just looks the plugins up from a pre-populated Dictionary.
While I'm still not really convinced that IoC/DI is better in this situation, I definitely have seen benefit as the project's scope crept. For things like logging and configurability it most certainly is the right approach.
I look forward to experimenting with it more in future projects.

C#: Abstract Strategy base class serving as Abstract Factory for Strategy objects

I am trying to create a web-based tool for my company that, in essence, uses geographic input to produce tabular results. Currently, three different business areas use my tool and receive three different kinds of output. Luckily, all of the outputs are based on the same idea of Master Table - Child Table, and they even share a common Master Table.
Unfortunately, in each case the related rows of the Child Table contain vastly different data. Because this is the only point of contention I extracted a FetchChildData method into a separate class called DetailFinder. As a result, my code looks like this:
DetailFinder DetailHandler;
if (ReportType == "Planning")
DetailHandler = new PlanningFinder();
else if (ReportType == "Operations")
DetailHandler = new OperationsFinder();
else if (ReportType == "Maintenance")
DetailHandler = new MaintenanceFinder();
DataTable ChildTable = DetailHandler.FetchChildData(Master);
Where PlanningFinder, OperationsFinder, and MaintenanceFinder are all subclasses of DetailFinder.
I have just been asked to add support for another business area and would hate to continue this if block trend. What I would prefer is to have a parse method that would look like this:
DetailFinder DetailHandler = DetailFinder.Parse(ReportType);
However, I am at a loss as to how to have DetailFinder know what subclass handles each string, or even what subclasses exist without just shifting the if block to the Parse method. Is there a way for subclasses to register themselves with the abstract DetailFinder?
You could use an IoC container, many of them allows you to register multiple services with different names or policies.
For instance, with a hypothetical IoC container you could do this:
IoC.Register<DetailHandler, PlanningFinder>("Planning");
IoC.Register<DetailHandler, OperationsFinder>("Operations");
...
and then:
DetailHandler handler = IoC.Resolve<DetailHandler>("Planning");
some variations on this theme.
You can look at the following IoC implementations:
AutoFac
Unity
Castle Windsor
You might want to use a map of types to creational methods:
public class DetailFinder
{
private static Dictionary<string,Func<DetailFinder>> Creators;
static DetailFinder()
{
Creators = new Dictionary<string,Func<DetailFinder>>();
Creators.Add( "Planning", CreatePlanningFinder );
Creators.Add( "Operations", CreateOperationsFinder );
...
}
public static DetailFinder Create( string type )
{
return Creators[type].Invoke();
}
private static DetailFinder CreatePlanningFinder()
{
return new PlanningFinder();
}
private static DetailFinder CreateOperationsFinder()
{
return new OperationsFinder();
}
...
}
Used as:
DetailFinder detailHandler = DetailFinder.Create( ReportType );
I'm not sure this is much better than your if statement, but it does make it trivially easy to both read and extend. Simply add a creational method and an entry in the Creators map.
Another alternative would be to store a map of report types and finder types, then use Activator.CreateInstance on the type if you are always simply going to invoke the constructor. The factory method detail above would probably be more appropriate if there were more complexity in the creation of the object.
public class DetailFinder
{
private static Dictionary<string,Type> Creators;
static DetailFinder()
{
Creators = new Dictionary<string,Type>();
Creators.Add( "Planning", typeof(PlanningFinder) );
...
}
public static DetailFinder Create( string type )
{
Type t = Creators[type];
return Activator.CreateInstance(t) as DetailFinder;
}
}
As long as the big if block or switch statement or whatever it is appears in only one place, it isn't bad for maintainability, so don't worry about it for that reason.
However, when it comes to extensibility, things are different. If you truly want new DetailFinders to be able to register themselves, you may want to take a look at the Managed Extensibility Framework which essentially allows you to drop new assemblies into an 'add-ins' folder or similar, and the core application will then automatically pick up the new DetailFinders.
However, I'm not sure that this is the amount of extensibility you really need.
To avoid an ever growing if..else block you could switch it round so the individal finders register which type they handle with the factory class.
The factory class on initialisation will need to discover all the possible finders and store them in a hashmap (dictionary). This could be done by reflection and/or using the managed extensibility framework as Mark Seemann suggests.
However - be wary of making this overly complex. Prefer to do the simplest thing that could possibly work now with a view to refectoring when you need it. Don't go and build a complex self-configuring framework if you'll only ever need one more finder type ;)
You can use the reflection.
There is a sample code for Parse method of DetailFinder (remember to add error checking to that code):
public DetailFinder Parse(ReportType reportType)
{
string detailFinderClassName = GetDetailFinderClassNameByReportType(reportType);
return Activator.CreateInstance(Type.GetType(detailFinderClassName)) as DetailFinder;
}
Method GetDetailFinderClassNameByReportType can get a class name from a database, from a configuration file etc.
I think information about "Plugin" pattern will be useful in your case: P of EAA: Plugin
Like Mark said, a big if/switch block isn't bad since it will all be in one place (all of computer science is basically about getting similarity in some kind of space).
That said, I would probably just use polymorphism (thus making the type system work for me). Have each report implement a FindDetails method (I'd have them inherit from a Report abstract class) since you're going to end with several kinds of detail finders anyway. This also simulates pattern matching and algebraic datatypes from functional languages.

Categories