Using Add with ForSingletonOf in StructureMap - c#

If have two classes Class1 and Class2 both implementing an interface IInterface.
And now, if I need a singleton instance of each of these classes, would this be the right way to implement it?
c.ForSingletonOf<IInterface>().Use<Class1>().Named("Class1");
c.ForSingletonOf<IInterface>().Add<Class2>().Named("Class2");
And then getting the instances like this:
container.GetInstance<IInterface>("Class1");
container.GetInstance<IInterface>("Class2");
Is there anything wrong in this approach or is there a better approach?

If you want access to a specific implementation of IInterface you will need access to the container in order to request the specific named instance.
Constructor injection will always provide you with Class1 as that is what you have told structuremap to use for IInterface. So this will probably lead you to pass the container around which is a very bad idea.
If the objects need to be created as singletons, I would suggest not injecting as IInterface but as Class1 and Class2. They are first class citizens in your application and qualify for direct access.
c.ForSingletonOf<Class1>().Use<Class1>();
c.ForSingletonOf<Class2>().Use<Class2>();
Depending on what blogs you read, you may want to specify the implementation of Class1 and Class2 as interfaces attributing to what purpose they provide. This way you future proof them if the backing singleton of IClass1 or IClass2 should change.
public interface IClass1 : IInterface { }
public interface IClass2 : IInterface { }
-----
c.ForSingletonOf<IClass1>().Use<Class1>();
c.ForSingletonOf<IClass2>().Use<Class2>();
That is how I would go about it. Named instances in the container I have found are only useful when configuring the container as I have access to it. When it comes to dependency injection they are not useful as the named instance you require is specified by the class/interface name. If you require more than one implementation of the same interface, they qualify for their own interface imo

Related

Dependency injection with abstract class

I am struggling for last two days to get a grip of DI.
I have two problems:
If I have a some common functionality why I can't do the same thing implementing DI with an abstract class?
In my example I have many class instance created under writefile, so should I move out all object creation from there? What if I have a layered design? Should these classes be passed all along?
public interface IWriteFile
{
void write();
}
public class WriteXMLFile : IWriteFile
{
public void write()
{
}
}
public class writefile
{
IWriteFile _file;
public writefile(IWriteFile file)
{
_file = file;
}
public void WriteMyFile()
{
_file.write();
}
}
Regarding your first point:
Let's say you want to test something that uses your abstract class. If you're directly using an abstract class, then if you want to do something different in the shared functionality in the common class, there's not much you can do.
With an interface, you've broken the coupling with the dependency. This is what the Dependency Inversion Principle in SOLID is talking about when it says "High-level modules should not depend on low-level modules. Both should depend on abstractions". Your class shouldn't depend on the lower-level class (even if it's an abstract class) to get its work done. Both the lower-level and higher-level class should depend on the interface which defines how they are going to interact. Using an interface helps separate the two, giving you loose coupling. Something else can handle wiring them together.
Regarding your second point:
Powerful DI frameworks actually handle a lot of this complexity for you.
Let's say you have a class - Thing - that has a bunch of dependencies.
public Thing(
IThingRepository repository,
IEmailer emailer,
ILogger logger,
INeedMoreStuff stuff
) : IThing
When you set up your IoC container, you'd do something like the following to associate which implementation to use for each interface:
IoC.Register<MySqlThingRepository>().As<IThingRepository>();
IoC.Register<MicrosoftExchangeEmailer>().As<IEmailer>();
IoC.Register<TruncatingFileLogger>().As<ILogger>();
IoC.Register<MoreStuff>().As<INeedMoreStuff>();
IoC.Register<Thing>().As<IThing>();
Then you can simply do:
IThing thing = IoC.Resolve<IThing>();
These fancy frameworks handle getting all the dependencies for you (since you told it how to get them) and will construct a Thing for you.
That being said, sometimes a fancy framework like that is overkill. In those cases, I usually use the factory pattern to abstract out the details of creating an object while still making sure the object being created follows good DI principles like constructor injection of its dependencies.
Regarding your polymorphism and interfaces:
Someone described polymorphism as simply "Same interface, different implementation. Substitutability". Wikipedia defines it as "the provision of a single interface to entities of different types". According to those definitions, I think using interfaces doesn't go against polymorphism. I feel in C# interfaces are usually sufficient for providing different implementations of the same "interface".
Yes, you can use an abstract base class to do the same thing, but I'd only use that if there's a common set of functionality I can factor out into the base class to keep my code DRY.
Regarding multiple implementations for an interface with StructureMap
I don't how StructureMap handles this, but presumably there's some logic that will decide when you want to use Thing1 versus Things2. You might be able to provide a delegate to StructureMap that it can use to get an IThing which would contain that logic.
Alternatively, you can have a factory that takes some parameters and decides which IThing to return. There are situations where I've put an interface on my factory and constructor injected that, or alternatively have the factory creating the object using IThing use the ThingFactory to get the right one.

Why using an Interface, what is wrong with classes and inheritance

I know that this question might be asked for many times in this website. I have read the other posts and read some books about why we have to use interfaces. All those posts and books say that, interfaces are like classes but they can only contain functions and all the classes that implement them should also implement their methods.
So I basically know what they are but I don't understand why should I write an interface at all, when I can make a superclass and extend the my other classes to that superclass without rewriting inherited functions again and again.
I would really appreciate if someone explains that to me please.
The key point of using interfaces is to create loosely coupled types. This is because interfaces are completely abstract and each class that implements them should have its own particular implementation of the interface’s methods.
If you create a base class instead of an interface, all the derived classes are tightly coupled with the base class. In particular situations, this tight coupling can cause some problems. The simplest and the most digestible problem that this tight coupling can cause is to create statically bound behaviors which can limit the code to a particular context. On the other hand loosely coupled types are dynamically bound which means they are more general and more reusable.
For example: imagine that you have one class named Service and another named Customer, if you do:
class Service {
public void RenderService() {…}
…
}
class Customer: Service {
public Customer () {…}
…
}
The Customer class in this example in tightly coupled with the Service class. Imagine if we want to introduce a new Service called Service2. Now, our Customer class will become useless and we need to also introduce another class like Customer2.
Now imagine the use of an interface:
interface IService {
void RenderService();
}
class Service: IService {
public void RenderService() {…}
}
class Customer {
IService service;
public Customer(IService service) {
this.service = service;
}
}
Using this technique (also known as Dependency Injection) you can introduce Service2 by creating another class which also implements the IService interface and still keep your Customer class useful and prevent the need to rewrite it.
Apart from this, there are other reasons to use interfaces such creating highly general (i.e. polymorphic) types or methods. So, as a conclusion, there’s a huge difference between simply writing classes and using inheritance and introducing an interface to your code. I hope I could help you digest the use of interfaces.

Why Use Interfaces Instead of Abstract Classes With DI?

I am beginning my journey of learning about dependency injection, and one of the reasons that I saw why it is a good idea to use DI was that it explicitly specifies your dependencies, which also makes your code more clear.
I have also noticed that interfaces are used abundantly, but I want to know why would we not use abstract classes for the sole purpose of specifying a default constructor?
Of course no implementation could be included in the abstract class.
Wouldn't this:
abstract class FooBase
{
protected IBar _bar;
FooBase(IBar bar)
{
_bar = bar;
}
abstract void DoSomething();
abstract void DoSomethingElse();
}
Demonstrate more clearly what the dependency of a FooBase object is more than:
interface IFoo
{
IBar Bar { get; }
void DoSomething();
void DoSomethingElse();
}
?
Please keep in mind I am new to this whole concept so be nice :)
One technical reason - forcing particular parent class in languages without multiple inheritance (Java/C#) will significantly restrict freedom of implementation of the "interface".
Note that there are 2 concepts hidden behind "interface" word and it sort of make it harder to reason in C#:
"interface" and abstract concept: well defined set of properties/methods to interact with an object; contract to work with an object.
"interface" as type in particular language (C#/Java) - one possible representation of
contract in given language.
Abstract/concrete classes can be used to represent contract, but force restrictions on implementers of contract in C#.
Some other languages (like C++) don't have such restriction and abstract classes is good option there. Other languages (i.e. "duck-types" JavaScript) does not have such class/interface distinction, but you can still have "contract" with an object.
Sample:
To provide more context where you should be hitting this restriction yourself in C#: DI is commonly used along with some form of TDD or at least with basic unit tests. So you try write some code and tests that uses abstract base class for DI.
abstract class Duck {
abstract void Quack();
}
class ConcreteDuck : Duck {...}
Now if you decide to write tests you may already have test classes that helps you to mock objects (if you are not using existing once)
class MockBase {...}
class MockDuck : MockBase,?????? // Can't use Duck and MockBase together...
Interface defines a contract. An Abstract base class defines a behavior.
Essentially, you can provide a single class that implements multiple interfaces,
which then in turn can be injected into multiple classes, but you will only have
a single abstract base class (at least in C#).
Consider the point of registering a type at the container (the composition root at best)
and consider the point where you resolve the dependency (the constructor or a property).
This SO will cover some more aspects SO on interface vs base class
In .NET, you only have single inheritance. In languages/frameworks where this is the case, opting to use an abstract class as your abstraction gives the potential to "burn the base class".
This means that you force the implementer of your abstraction to inherit from a singular class, when forcing them to do so might result in inconveniencing them severely, depending on what the implementation is.
Let's say that you have your abstract class Contract. If someone has their own Base class that they want to use which exposes only protected methods (for inheritors).
Because the methods are protected, one can't use encapsulation (an instance of Base stored in a field) to access the methods in Base for your abstraction implementation.
Even worse, if you don't have access to modify Base, then you might have to resort to some very ugly workarounds (Reflection, namely).
That said, with interfaces, you give the implementer the choice of where to inherit from and don't limit their options.
The typical pattern you'll see is that you always provide an interface for your contract and code your consumers against the interface. You also provide an abstract base class that provides functionality that people may derive from for convenience, but are not obligated to derive from.
Also, if it's possible for you to provide this functionality in the form of something that is easily encapsulated (for the condition I describe above), it would be even more optimal (you'd have an abstract class which just calls the instance that exposes the methods).

Interface instantiation vs class instantiation

Could someone please helpme to understand if the following codes are same. If not what's the difference between class and interfance instantiation.
IUnityContainer container = new UnityContainer()
UnityContainer container = new UnityContainer()
As far as I understand Inteface has only method signature and if the interface has been implemented by 3 classes. Not too sure which of the 3 instance would be created by first statement above.
Thankyou.
Interfaces can't be instantiated by definition. You always instantiate a concrete class.
So in both statements your instance is actually of type UnityContainer.
The difference is for the first statement, as far as C# is concerned, your container is something that implements IUnityContainer, which might have an API different from UnityContainer.
Consider:
interface IAnimal
{
void die();
}
class Cat : IAnimal
{
void die() { ... }
void meow() { ... }
}
Now :
IAnimal anAnimal = new Cat();
Cat aCat= new Cat();
C# knows for sure anAnimal.die() works, because die() is defined in IAnimal. But it won't let you do anAnimal.meow() even though it's a Cat, whereas aCat can invoke both methods.
When you use the interface as your type you are, in a way, losing information.
However, if you had another class Dog that also implements IAnimal, your anAnimal could reference a Dog instance as well. That's the power of an interface; you can give them any class that implements it.
There's really no such thing as "interface instantiation", but there are interface variables. The first line is an example of one such variable.
With the first line, you could instantiate container to be any concrete class that implements IUnityContainer. With the second line, the container object could only be instantiated from the UnityContainer class or a derived class.
When you use interface variables in your code, it allows you to more easily switch out the concrete implementation, which makes your code more flexible.
Interface instantiation is not possible. But when we created an an object for interface using its implemented class it works.
IUnityContainer container = new UnityContainer()// It is assigning an object of its implemented class.
UnityContainer container = new UnityContainer() // To access directly by using like this.
Assume that there is a multiple inheritance, to achieve this we need to go with first.
There is no need to provide such things we go with second way.
Interfaces restricts direct access of the data and members of its class.
The object instantiated and stored in the IUnityContainer container variable is considered by the compiler to have only the members defined in the IUnityContainer interface. That is, if the UnityContainer class contains members that aren't defined by the IUnityContainer interface, you won't be able to invoke them. On the other hand, you could "put" any object that implements the IUnityContainer interface in the IUnityContainer container variable--not just instances of UnityContainer. With the second declaration, you're stuck with instances of UnityContainer and objects in its inheritance hierarchy.
Check out the C# Programming Guide to Interfaces for more information on interfaces and how they're used.

I think I missed something on the "Programming to an interface" concept

So I am still very new to C# and using interfaces, and when I thought I understood them I realized I don't completely. The confusion I have found that I am seeking some clarification here for is, when you create an interface, and have a class inherit from it
public Interface ISomeInterface
{
//some methods/properties
}
public class FooClass : ISomeInterface
{
//implemented ISomeInterfaces methods/properties
}
And you use this class object in an implementation somewhere in your program
public class BarClass
{
private ISomeInterface _someInterface;
public BarClass(ISomeInterface someInterface)
{
_someInterface = someInterface;
}
//rest of class
}
My confusion is why do I see it setup this way. I thought that I would have instantiated a new object of type FooClass, as well as used an object of type FooClass in the constructor as such:
public class BarClass
{
private FooClass _fooClass;
public BarClass(FooClass fooClass)
{
_fooClass = fooClass;
}
//rest of class
}
What am I missing to understanding this? I didn't think I would directly be declaring objects of an Interface?
Thanks in advance.
The idea is that BarClass should not be tightly coupled to a specific implementation of ISomeInterface.
If you use this:
public BarClass(FooClass fooClass)
it means that the BarClass can work only with this specific FooClass implementation and nothing else. Whereas if you use:
public BarClass(ISomeInterface fooClass)
now the BarClass is no longer tightly coupled to FooClass. This means that the consumer of the BarClass can now pass any implementation of the interface he wants as long as it respects the defined contract (interface). So if he wants FooClass he passes an instance of FooClass, but if he is not satisfied with FooClass he can write his own implementation and pass it to the constructor and from the point of view of the BarClass this is absolutely transparent (it doesn't need to be modified).
The weak coupling between your classes is one of the most fundamental aspects of OOP as it allows you to easily replace one component with another without having to rewrite your entire application.
Suppose FooClass wrote something to a database. You'd like to test BarClass without having to actually set up a database. If you created a different TestFoo that implemented the same interface, you could pretend to be the database and more easily test your class; BarClass wouldn't have to know that it wasn't talking to the 'real' FooClass.
Do you have a C/C++ background? Then you should be aware that
private ISomeInterface _someInterface;
would be written as
private:
ISomeInterface& _someInterface;
In C++ (assuming you have an abstract base class called ISomeInterface).
This means you are storing a reference to an object implementing ISomeInterface not such an object itself. The advantage of this is that you can pass ANY object to BarClass that implements ISomeInterface which gives you more flexibility, e.g. for unit testing.
By using the interface definition instead of the concrete implementation, your code is now more loosely coupled. This technique is used in dependency injection.
In addition, this comes in handy when you need to need to implement FooClass differently. If you used the concrete implementation, you will need to make code changes where ever you have declared FooClass. Programming against the interface shields you from the effects of such changes.
One of the main benefit to program to ISomeInterface instead of FooClass, is that you might probably change your implementation of FooClass. For example, consider a database driven blog application:
interface IBlogStorage{
getPosts();
}
you then have a class like:
class XMLBlogSotrage: IBlogStorage{}
and suppose you implement everything to the interface. later on, you think XML is too slow and you want to use RDBMS, then:
class MsSQLBlogStorage:IBlogStorage{}
In this case, you don't need to change anything in other codes, you just need to create a new class and plug it in! Those already existed codes, doesn't need to bother where is the storage.
Another way of thinking about the interplay between interfaces and classes is to flip them upside down. That means to start with classes first. Let's say you have several classes that expose a method called "Sort()". Then you have another class that has a method that requires references to these classes and in turn calls their "Sort()" methods. Instead of having several methods with different parameters, you can create and attach an interface to those classes (very quick fix as these classes already contain the implementation).
A.Sort()
B.Sort()
C.Sort()
interface ISortable {void Sort();}
A : ISortable
B : ISortable
C : ISortable
D.SortSomething(ISortable foo)
{
foo.Sort()
}
Maybe this is too abstract. My favorite use of interfaces is enabling my classes to participate in foreach loops.
class SomeCollection : IEnumerable
{
List<SomeItem> _items = new List<SomeItem>();
// This is the only code I need to enable this class to participate in foreach loop.
public Enumerator GetEnumerator()
{
return _items.GetEnumerator();
}
}
Once you discover how interfaces can simplify your codes, you can even begin creating interfaces before writing your classes.

Categories