Interface injection - c#

Is it possible to inject an interface into an existing 3rd party class that I can not alter? Like extension methods but for an interface (and its implementation for the class that it had been injected to).
I like to optionally use one of two similar 3rd party libraries by giving classes that are similar in both libraries the same interfaces. So that I do not have to convert there classes into mine.

I don't completely understand what you mean about injecting an interface, but you could use the Adapter pattern to achieve this. See also: http://dofactory.com/Patterns/PatternAdapter.aspx
Create your own interface, then create your own classes that implement the interface, which contain/wrap the 3rd party classes.

As long as you're dealing with interfaces, why not just go with wrapping the classes in your own classes, that implement the interfaces?

You should look at the Decorator Pattern which allows you to extend a class by composition.
e.g.
Given sealed class A which implements InterfaceA:
public interface InterfaceA
{
int A {get; set;}
}
public sealed Class A : InterfaceA
{
public int A {get;set;}
}
You could extend InterfaceA and then use a decorator class B to encapsulate an instance of class A and provide additional methods.
public interface MyExtendedInterfaceA : InterfaceA
{
int B {get;set}
}
public class B : MyExtendedInterfaceA
{
private InterfaceA _implementsA = new A();
public int A
{
get
{
return _implementsA.A;
}
set
{
_implementsA.A = value;
}
}
public int B {get; set;}
}
Alternatively, decorator Class C could add a whole new interface:
public interface InterfaceC
{
int MethodC();
}
public class C : InterfaceA, InterfaceC
{
private InterfaceA _implementsA = new A();
public int A
{
get
{
return _implementsA.A;
}
set
{
_implementsA.A = value;
}
}
public int MethodC()
{
return A * 10;
}
}

Related

Add common method to classes inheriting from a C# Interface?

I have an interface such as this one:
public interface ITestInterface
{
int a { get; set; }
void DoSomething();
}
Some of my classes are deriving from this interface:
public class OneClass : ITestInterface
{
public int a { get; set; }
public void DoSomething()
{
Console.WriteLine(this.a.ToString());
}
}
public class AnotherClass : ITestInterface
{
public int a { get; set; }
public void DoSomething()
{
Console.WriteLine((this.a * 2).ToString());
}
}
Since I now need a (large) common method on all classes derived from my interface, I was trying to provide an additional base class for that:
public class MyBaseClass
{
public void LargeCommonMethod()
{
Console.WriteLine((this.a * 3).ToString()); // no 'a' on base class
}
}
This clearly doesn't work because the base class would also need to implement my interface in order to know about that a field.
I am now asking myself what the best approach would be here:
make MyBaseClass inherit from ITestInterface?
set LargeCommonMethod() to protected and provide all internal data it uses via arguments? (There's actually a lot of these..)
skip the interface all along and replace it with an abstract base class?
...?
C# 8 provides a feature precisely for this scenario.
Your classes all implement an interface
You want to add a method to the interface
You don't want a breaking change to all of the existing classes. If you add a method to the interface all of the classes will break unless you find some way to add the method to all of them. (That includes modifying them all to inherit from a new base class.)
That feature is default interface methods.
You can add your method and a default implementation to the interface:
public interface ITestInterface
{
int a { get; set; }
void DoSomething();
void LargeCommonMethod()
{
Console.WriteLine((this.a * 3).ToString());
}
}
Your existing classes that implement the interface will not break. When cast as the interface, you'll be able to call the method which is defined in the interface. You can still modify any class to provide its own implementation, overriding the interface's default implementation.
For the method to be available the object must be cast as the interface - ITestInterface.
A lot of developers - including myself - found this to be an odd feature. But this is the scenario it's for.
Some documentation
The most common scenario is to safely add members to an interface already released and used by innumerable clients.
If you require a base implementation for a method then an interface is clearly not the way to go.
I would choose an abstract class instead and get rid of the interface. There is no need to complicate the design basically.
The Adapter pattern could fit your Use case, when you want to keep the ITestInterface consistent:
public interface ITestInterface
{
int a { get; set; }
void DoSomething();
}
public class TestInterfaceAdapter : ITestInterface
{
private readonly ITestInterface _testInterface;
public int a {
get => _testInterface.a;
set => _testInterface.a = value;
}
public TestInterfaceAdapter(ITestInterface testInterface)
{
_testInterface = testInterface;
}
public void DoSomething()
{
_testInterface.DoSomething();
}
public void LargeCommonMethod()
{
Console.WriteLine((this.a * 3).ToString());
}
}
public class OneClass : ITestInterface
{
public int a { get; set; }
public void DoSomething()
{
Console.WriteLine(this.a.ToString());
}
}
public class AnotherClass : ITestInterface
{
public int a { get; set; }
public void DoSomething()
{
Console.WriteLine((this.a * 2).ToString());
}
}

C# Is there a way of implementing interfaces for classes from dlls?

I'm using a dll with a lot of classes. I'd like to implement dinamically interfaces for these classes, then I can unit test them by mock.
Is there a way of doing it?
Example:
The dll has a class Comunicator
public class Comunicator
{
public void Execute()
{
//execute something
}
}
Is there a way of doing this class implementing the interface below dinamically?
public interface IComunicator
{
void Execute();
}
This way I want that the property below
public IComunicator Comunicator{ get; set; }
Be able to understand this assignment
Comunicator = new Comunicator();
Is there a way of doing this class implementing the interface below dynamically?
Short Answer: NO
If the dll is a 3rd party library then there is nothing you can do to modify that class as you have no control over it.
You could however create your own classes and abstraction to encapsulate the 3rd party dependency.
You create your desired interface
public interface IComunicator {
void Execute();
}
And either using encapsulation
public class MyCommunicator : ICommunicator {
private readonly Communicator communicator = new communicator();
public void Execute() {
communicator.Execute();
}
}
or inheritance (if the class is not sealed)
public class MyCommunicator : Communicator, ICommunicator {
}
This way the property below
public IComunicator Comunicator{ get; set; }
Will be able to understand this assignment
obj.Comunicator = new MyComunicator();

4 Classes with the same properties and methods - is it possible to create only one?

i have another question open here on SO and after thinking about it, i may be approaching this in the wrong way.
i have 4 classes, that have the same properties and methods.
some of the classes, have their own properties and methods ( not overrides of the existing ones ).
currently i create each class as:
public class ClassOne
{
public ClassOne()
{
}
public int ID {get;set;}
// More properties here
public void Set(){
// Do Stuff to save this
}
// More Methods here
}
cant i create one class that will generate all of the 4 classes?
and in the classes themselfs i only create specific properties/methods for that class?
repeating the code seems very odd to me, im sure there must be a way to do this, just dont know how.
Your situation is one of the main reasons why inheritance was invented. So with that, you can write
public class Base
{
// Properties and methods common to all
}
public class ClassOne : Base
{
// Properties and methods specific to ClassOne
}
public class ClassTwo : Base
{
// Properties and methods specific to ClassTwo
}
public class ClassThree : Base
{
// Properties and methods specific to ClassThree
}
public class ClassFour : Base
{
// Properties and methods specific to ClassFour
}
As requested, more code, using interfaces and abstract classes:
An interface is just a blueprint, defining what properties and methods are required to be compatible with other "BaseClasses"
public interface IBaseClass
{
public int ID {get;set;}
public void Set();
}
Abstract classes can contain code, but can not be instantiated, they are form of starting point for a class, but not a complete class themselves.
public abstract class ABaseClass : IBaseClass
{
public int ID {get;set;}
public void Set(){
// Do Stuff to save
}
}
Each class inherits from the abstract class and can then override and implement whatever it wants, customizing it however is necessary.
public class ClassOne : ABaseClass
{
}
public class ClassTwo : ABaseClass
{
}
public class ClassThree : ABaseClass
{
}
public class ClassFour : ABaseClass
{
}
ps. not entirely sure if my syntax is 100% correct
Could you simply make a base class with your properties and inherit from that class?
Why not use inheritance??
public class ClassOne
{
public ClassOne()
{
}
public virtual int ID {get;set;}
// More properties here
public virtual void Set(){
// Do Stuff to save this
}
// More Methods here }
public class ClassTwo : ClassOne
{
public string ClassTwoString { get; set; }
}
public class ClassThree : ClassOne
{
public string ClassThreeString { get; set; }
}
Can you make them all inherit off of the same class? If so, that sounds ideal.
Barring the possibility of making them inherit, you could write an interface that describes the methods and properties which each of them use. Then you can call each instance of the class through the same interface.
Barring again that possibility, you could write a reflective assignor/accessor. But you shouldn't do that.

Accessing a method which is not on the base Interface

I have a design issue and am looking for the best design solution. I have added an example of the issue below.
public interface IVehicle<T>
{
int GetEngineSize();
}
public class Car : IVehicle<Car>
{
public int GetEngineSize()
{
throw new NotImplementedException();
}
public bool HasSpolier()
{
return true;
}
}
public class Bus : IVehicle<Bus>
{
public int GetEngineSize()
{
throw new NotImplementedException();
}
}
public abstract class BaseController<T>
{
public IVehicle<T> Repository { get; set; }
}
public abstract class CarController : BaseController<Car>
{
public CarController()
{
// How can I access the HasSpolier method from the IVehicle<T> without having to cast the Interface to concrete class Car
bool result = Repository.HasSpolier();
}
}
I'm not sure your generics are doing what you want here.
If instead of
IVehicle<T> Repository {get; set;}
You did
T Repository {get; set;}
You could make
public abstract class BaseController<T> where T : IVehicle
To ensure that they're of the IVehicle Interface
Then you'd have a typed repository and get access to your spoiler method.
You're doing IVehicle<Bus> but at least in the sample code, the T is never used in the interface. At this point the T is worthless.
Unless you implement the method in the interface, you can't access it without casting it to another class.
You'd have to cast your Repository to Car.
It would make using your interface pointless as the dependency on the implementation which you're trying to remove is re-introduced.
Also the type parameter on your interface isn't required, you don't use it anywhere else in the interface...
public interface IVehicle
{
int GetEngineSize();
}

C#: Multiple Inheritance with Non-Abstract Computed Properties

I'm creating a series of Interfaces/Abstract classes that contain basic properties and I would like to have computed Properties and multiple inheritance.
public abstract class /interface Modifiable
{
public DateTime ModifiedDate {get; set;}
public boo ModifiedToday
{
get { return DateTime.Now.AddDays(-1).CompareTo(ModifiedDate) >= 0; }
}
public bool ModifiedInLastWeek
{
get { return DateTime.Now.AddDays(-7).CompareTo(ModifiedDate) >= 0; }
}
}
public abstract class /interface Deletable
{
public DateTime DeletionDate {get; set;}
public bool Deleted
{
get { return DeletionDate != default(DateTime) }
}
}
Then I have a class that inherits from these two Interfaces/Abstract classes.
public class Something : Modifiable, Deletable
{
//
}
But a class cannot inherit from two abstract classes. So I then need to use interfaces, but with interfaces I cannot have method bodies. I then have to define the same exact functions across multiple classes to implement these simple bool properties using interfaces.
I also don't want to have Modifiable inherit from Deletable because I might want something to be Modifiable but not Deletable. These specific classes aren't my problem, I'm simply using them to illustrate my problem.
Is there a design pattern that mimics an abstract class by allowing function bodies, but allows multiple inheritors like an interface?
It's not multiple inheritance, but something that comes to mind is Extension methods.
public interface IModifiable
{
DateTime ModifiedDate {get; set;}
}
public static class ModifiableExtensions
{
public bool ModifiedToday(this IModifiable m)
{
return DateTime.Now.AddDays(-1).CompareTo(m.ModifiedDate) >= 0;
}
public bool ModifiedInLastWeek(this IModifiable m)
{
return DateTime.Now.AddDays(-7).CompareTo(m.ModifiedDate) >= 0;
}
}
That gives the "feel" of helper methods that are baked into the type, but they happen to be declared elsewhere. Take this class:
public class MyModifiable :IModifiable
{
public ModifiedDate {get; set;}
}
And you can do this:
MyModifiable m = new MyModifiable;
m.ModifiedDate = DateTime.Now;
bool isToday = m.ModifiedToday();
No. C# doesn't have a mechanism to implement multiple inheritance this way.
When it comes to interfaces, this is possible because when you define multiple interfaces you also need to implement them all.
Consider a different design, possibly using composition in order to reuse the classes you want to use for multiple inheritance.
I forget the design pattern name, but there's a pattern to implement multiple interfaces by wrapping the method/property calls around interface implementations of members who are of that same interface:
interface IDrivable {
void Drive();
}
interface IFlyable {
void Fly();
}
class Car : IDrivable {
public void Drive() { /* Implementation */ }
}
class Plane : IFlyable {
public void Fly() { /* Implementation */ }
}
class MyClass : IDrivable, IFlyable {
private IDrivable _car = new Car();
private IFlyable _plane = new Plane();
public void Drive() { _car.Drive(); }
public void Fly() { _plane.Fly(); }
}
Yes there are methods, several, actually. A few thoughts:
Use an empty interface for Deletable, Modifiable etc (called marker interfaces), then create extension methods for them. This is not as expandable as multiple inheritance, but it gets a long way.
Use genericity, possibly with the same tagging interfaces to create dependencies. This way you can have a base class with all methods for both Modifiable and Deletable, including abstract methods and override implementation in derived classes
Use aspect oriented programming to get to the same results
Almost the same, but do it yourself with Castle or similar library, possibly with the help of attributes.
Obviously, none of the above has all the advantages of multiple inheritance. If you want multiple inheritance in .NET, you can use C++.NET or Eiffel.NET.
Sorry, multiple inheritance is not possible in C# and that's a bummer for you. Your choices are:
Either to chain your base class inheritance a la MyClass : MyBaseClass : EvenBasierClass
Or inherit from multiple interfaces. And implement all methods of all interfaces.
It's not pretty, but you can also control property accessibility or return values inside your classes by checking the instance type.
Modifiable & Deletable IMO should be interfaces, not base classes. A base class defines what a type is, whereas a interface describes what a type does.
As far as implementing the code, you can always use extension methods:
public interface IModifiable
{
public DateTime ModifiedDate {get; set;}
}
public interface IDeletable
{
public DateTime DeletionDate {get; set;}
}
public static class SomeExtentions
{
public static bool IsModifiedToday(this IModifiable modifiable)
{
return DateTime.Now.AddDays(-1).CompareTo(modifiable.ModifiedDate) >= 0;
}
public static bool IsModifiedInLastWeek(this IModifiable modifiable)
{
return DateTime.Now.AddDays(-7).CompareTo(modifiable.ModifiedDate) >= 0;
}
public static bool IsDeleted(this IDeletable deletable)
{
return deletable.DeletionDate != default(DateTime);
}
}
I would probably use delegation to achieve this. Create Modifiable and Deletable as interfaces, then create implementations of those. Give the Something class instances of these implementations. Here's an example for Deletable:
public interface Deletable
{
DateTime DeletionDate{get;set;}
bool Deleted{get;}
}
public class DeletableImpl : Deletable
{
public DateTime DeletionDate{get; set;}
public bool Deleted{get {return DeletionDate != default(DateTime);}}
}
// Do the same thing with Modifiable and ModifiableImpl
public class Something : Deletable, Modifiable
{
private Deletable _deletable = new DeletableImpl();
private Modifiable _modifiable = new ModifiableImpl();
public DateTime DeletionDate
{
get{return _deletable.DeletionDate;}
set{_deletable.DeletionDate = value;}
}
public bool Deleted{get{return _deletable.Deleted;}}
public DateTime ModifiedDate {
// and so on as above
}

Categories

Resources