Create mock of class without calling original class constructor - c#

Say i have library with this code (that canot be changed)
namespace Library.Namespace;
public interface ISomething { }
internal class Something : ISomething {
public Something(...) {
...
}
}
public class Anything {
private Something _Something;
public Anything (ISomething something) {
_Something = (Something) something;
...
}
}
and i want to create mock of Anything class:
public MockAnything : Mock<Anything> {
public MockSomething Something { get; }
public MockAnything()
: this(new MockSomething()) {
}
public MockAnything(MockSomething something)
: base(something.Object) {
Something = something;
}
}
public MockSomething : Mock<ISomething> {
}
everythig good so far (aka compiller is happy), but at runtime im getting exception when calling:
var mock = new MockAnything();
var object = mock.Object; // <-- exception here
System.InvalidCastException
Unable to cast object of type 'Castle.Proxies.ISomethingProxy' to type 'Library.Namespace.Something'.
at Library.Namespace.Something..ctor(ISomething something)
at Castle.Proxies.AnythingProxy..ctor(IInterceptor[] , ISomething something)
any idea how to correctly mock class, that uses direct cast in constructor?

When using Moq, the best and easiest way is to create mocks based on interfaces. Unfortunately, you cannot change the library and add an interface there or get rid of the cast (which would be best anyway).
From a design perspective, I'd recommend to create a wrapper around the library code that you cannot change. In addition, you create an interface (let's call it IAnything) that contains the methods that you want to use. Instead of using Anything directly in your code, you'd inject IAnthing into your code. The following code outlines the necessary classes:
public IInterface IAnything
{
// Members of the original Anything class that you want to use in your code
}
public class AnythingWrapper : IAnything
{
private readonly Anything _anything;
public AnythingWrapper(Anything anything)
{
_anything = anything;
}
// IAnything implementation
}
While this might seem like a bit of extra work, it usually is done with some paste-and-copy. In addition, you create a layer of abstraction between your code and the library code. If the library changes in the future, you could be able to apply the changes in your wrapper class without changing the interface as such.
As soon as you have created the interface, you can easily create a mock, e.g.:
var mockAnything = new Mock<IAnything>();

Related

C# 8 default interface implementation and inheritance

I want to use C# 8 default interface implementation to face a performance issue in my code.
Actually, I have this intefaces :
public interface IDataAdapter {}
public interface IDataAdapter<T> : IDataAdapter
{
void Insert(T value);
}
I actually have to do reflection across all IDataAdapter, check generic type and call Insert by reflection for a specific T instance. What I wish to do is :
public interface IDataAdapter
{
void InsertValue(object value);
}
public interface IDataAdapter<T> : IDataAdapter
{
void Insert(T value);
public void InsertValue(object value) => Insert(value as T);
}
The compiler says to use the keyword new to mask the inherited method. However, the only thing I'm trying to accomplish is to have a non-generic method already implemented to make all IDataAdapter<T> implementations to only have to implement the generic version.
Is this something I can accomplish or it's still impossible ? I already know that using an abstract class is a way to solve this issue, but I want to allow a developper to have a class that implements many IDataAdapter...
This is my current reflection code :
public IEnumerable<IDataAdapter> DataAdapters { get; }
public Repository(IEnumerable<IDataAdapter> dataAdapters)
{
DataAdapters = dataAdapters;
}
public async Task SaveAsync()
{
foreach (var item in aggregates)
{
foreach (var dataAdapter in DataAdapters)
{
if (dataAdapter.GetType().GetInterfaces().Any(i => i.IsGenericType && i.GetGenericArguments()[0] == item.GetType()))
{
dataAdapter.GetType().GetMethod("Insert", new[] { item.GetType() }).Invoke(dataAdapter, new[] { item });
}
}
}
}
From an object oriented point of view, what you are trying to do can't be done.
Suppose you create the following class hierarchy:
public interface IFoo{}
public interface IBar{}
public class A: IFoo{}
public class B: IFoo{}
public class C:IFoo,IBar {}
And then the following adapters:
public class TestA : IDataAdapter<A>{}
public class TestB : IDataAdapter<B>{}
public class TestC : IDataAdapter<C>{}
public class TestIFoo : IDataAdapter<IFoo>{}
public class TestIBar : IDataAdapter<IBar>{}
public class TestIBoth : IDataAdapter<IFoo>,IDataAdapter<IBar>{}
What should happen if TestA receive an instance of A is quite easy. But what about TestIFoo receive a C? Currently your reflection code won't work because you test type equality (does C equals IFoo? No! Even if C as IFoo is ok).
This breaks Liskov substitution principle. If something works with a class then it should also work with any of its subclasses.
Let's suppose you fix above point. Now what about TestIBoth receiving a C? Is there two different implementation of Insert in it? Of course, this is required by inheritence! But then... do you have to insert C twice? Or do you have to insert it just once in the first fitting method?
The reason why you have to go through reflection is because all those questions needs an algorithmic answer. Your compiler won't be able to answer (which makes the language prevent it by the way)
In the end I would strongly recommend to use a very different solution (like the one proposed by Wim Coenen)
I recognize this problem where you need to look up the IDataAdapter implementation which knows how to handle a certain type of item. I've done something similar for a "view plugin" system, where I would look for the view plugin that knows how to render a certain type. This is useful if you can't know in advance what type of objects you'll need to render.
As far as I know, trying to shoehorn more compile-time type safety into this pattern won't really work, or if it does then it won't actually provide any benefits. I would just declare IDataAdapter like this:
public interface IDataAdapter
{
void InsertValue(object value);
Type SupportedType { get; }
}
If a data adapter supports multiple types, you can make it IEnumerable<Type> SupportedTypes instead, or maybe replace the property by a bool SupportsType(Type) method.

Requirement to include reference to support an interface

Assume that I have a library which defines an interface:
namespace LibraryOne
{
public interface ISomething
{
void DoSomething();
}
}
I implement this in a second library
namespace LibraryTwo
{
public class Something : ISomething
{
public void DoSomething() { throw new Exception("I don't know how to do anything!"); }
}
}
I then use this class in a third library
namespace LibraryThree
{
public class MyClass
{
private Something myThing = new Something();
public void DoIt() {
myThing.DoSomething();
}
}
}
Visual Studio tells me that LibraryThree has to have a reference to LibraryOne for this code to work. Even if I make ISomething internal and make LibraryOne InternalsVisibleTo LibraryTwo, I still have to have that reference. Why?
If I actually referred to an ISomething, I'd understand. If I expected Something to behave like an ISomething, I'd understand. But I just need to treat it as a Something.
I just need to treat it as a Something
That's the thing: the moment you implement ISomething in Something, it becomes an ISomething too. The fact that a class implements an interface is integral to that classes nature.
Without this, you would be able to inherit Something to create SomethingElse, and that SomethingElse would not implement ISomething. Now consider this example:
public class Something : ISomething
{
public void DoSomething() { ... }
// Add this method
public void ProcessSomething(Something other) {
ISomething byInterface = other; // This is legal
// Now do something with byInterface
}
}
Your hypothetical code does this:
public class SomethingElse : Something {
...
}
Now pass an instance of SomethingElse to ProcessSomething to complete the circle: your SomethingElse is a Something but it is not ISomething, breaking the cast that C# expect to work unconditionally.
When the CLR executes your application, it loads all the information about the types referenced in your program.
Because Something implements ISomething, the CLR needs to know about the interface - so the .dll containing this interface has to be accessible to the executable.
Any time you have a library that calls another library you need both in your top level project. How else do you expect the top project to assemble all the necessary files during build?

how to use classes themselves as method parameters?

Its been a while but i need to convert some custom code into C# (i think it was called emeralds or something somebody else gave to me). there is a certain method that takes a class(any class without any object conversions). this is the code im trying to convert.
class management
Accessor current_class
Accessor class_Stack
def call(next_class) #method, called global, takes a "class" instead
#of a variable, kinda odd
stack.push(current_class) #stack handling
current_class = next_class.new #makes a new instance of specified next_class
end
end
next_class seems to be any class related to a base class and assigns a new instance of them to a variable called currentClass. there are other "methods" that do something similar. I've tried setting the parameter type to "object", but loses all the the "next_class" attributes that are needed. this is my attempt at it
public class management {
public Stack stack;
public Someclass currentClass;
public void Call(object nextClass) {
stack.push(currentClass); // stack handling
currentClass = new nextClass(); // conversion exception, otherwise loss of type
}
}
IS this even possible in C#
another thing this language seems to able to keep attributes(methods too) from Child classes when you cast them as a base class. e.g cast green bikes as just bikes but it will still be green
can somebody point me in the right direction here? or do i need to rewrite it and change the way it does things?
What you want is Generics and I think also, based on the fact that you call a method, Interfaces.
So your Interface will define "new" and the Class will inherit from the interface.
You can then pass the class as a generic and call the Interface method of "new" on it.
So;
public interface IMyInterface
{
void newMethod();
}
public class MyClass1 : IMyInterface
{
public void newMethod()
{
//Do what the method says it will do.
}
}
public class Class1
{
public Class1()
{
MyClass1 classToSend = new MyClass1();
test<IMyInterface>(classToSend);
}
public void test<T>(T MyClass) where T : IMyInterface
{
MyClass.newMethod();
}
}
EDIT
And check out "dynamic" in C# 4.0. I say this because if you don't know what the method is until runtime you can define it as dynamic and you are basically telling the compiler that "trust me the method will be there".
This is in case you can't use generics because the methods you call will be different for each class.

C# How to generate an object implementing different interfaces dynamically at runtime?

I'm looking at how to solve a problem and I'm not even sure this might be possible at all in C# & .NET 3.5:
Say I have a limited number of interfaces, each describing a specific, non-related set of methods. Now I have a number real-world devices which each may implement just a subset of these interfaces.
During set-up of comms with these devices they will tell me which capabilities they have. I would now like to create an object implementing the interfaces (each resembling one capability of the device) so that higher up in my application architecture I'm able to:
write code against the aforementioned interfaces
test if that generated object implements a certain interface to see if certain actions are supported
I'm not sure at all which approach to use towards this problem. Any comments or approaches most welcome!
Use a mocking framework such as Moq, RhinoMocks or TypeMock Isolator
If you're looking to do something lower level, things like Castle DynamicProxy might be a good direction for you.
Try something like LinFu.DynamicObject.
Maybe you don't need to make this so "dynamic".
Have you checked the Abstract Factory pattern? It seems that basically what you need is to create a concrete implementation for each of your interfaces based on a device type.
You don't need to have a single class implementing lots of interfaces, it is enough to have appropriate implementation of the specific interface when your code requests it.
Each concrete implementation of your abstract factory can generate several interface implementations based on your device type.
Example:
public interface IDeviceFactory
{
ISomething GetSomeInterface();
ISomethingElse GetSomeOtherInterface();
}
and then you implement the specific factory for each device:
public class SimpleDeviceFactory : IDeviceFactory
{
public virtual ISomething GetSomeInterface()
{ return Something.Empty; }
public virtual ISomethingElse GetSomeOtherInterface()
{ return new SomeSimpleConreteImplementation(); }
}
or maybe:
public class ComplexDeviceFactory : IDeviceFactory
{
public virtual ISomething GetSomeInterface()
{ return new ComplexStuff(); }
public virtual ISomethingElse GetSomeOtherInterface()
{ return new EvenMoreComplexStuff(); }
}
And then, finally, you create the right factory for your device:
public class DeviceFactory
{
public static IDeviceFactory CreateForDevice(IDevice device)
{
DeviceType type = device.Type; // or something like this
switch (type)
{
case DeviceType.Simple:
return new SimpleDeviceFactory();
case DeviceType.Complex:
return new ComplexDeviceFactory();
default:
throw new NotImplementedException();
}
}
}
Note that I have also marked IDeviceFactory method implementations as virtual, so that you can easily reuse or override specific interfaces for a specific device.
It is possible, just not easy. You need to make a string which is basically a source file and then create and use a CSharpCodeProvider, which you then order to compile your code. If it works, you can manually access your created objects through reflection.
For the interested, i did it a while back, the details are a bit foggy.
.NET 4 might make it easier, you could use one of the already mentioned framework or go the System.Reflection route. You'll find plenty of samples on the internet.
I've done both in the past. Rolling my own il.Emit stuff and using a framework (Spring.NET in my case). For anything but the trivial stuff, use one of the frameworks.
You can also try with the Re-mix project. One of the main features of this project is create mixins, that lets you add interfaces with implementations and state to other classes. Take a look this example:
using Remotion.Mixins;
using Remotion.TypePipe;
//...
public interface ITargetInterface
{
void DoSomething();
}
// . . .
public class TargetImplementation : ITargetInterface
{
public void DoSomething()
{
Console.WriteLine("ITargetInterface.DoSomething()");
}
}
// . . .
public interface IMixinInterfaceA
{
void MethodA();
}
// . . .
public class MixinImplementationA : IMixinInterfaceA
{
public void MethodA()
{
Console.WriteLine("IMixinInterfaceA.MethodA()");
}
}
// . . .
public interface IMixinInterfaceB
{
void MethodB(int parameter);
}
// . . .
public class MixinImplementationB : IMixinInterfaceB
{
public void MethodB(int parameter)
{
Console.WriteLine("IMixinInterfaceB.MethodB({0})", parameter);
}
}
Then you can merge those types to create a mixin:
var config = MixinConfiguration.BuildFromActive()
.ForClass<TargetImplementation>()
.AddMixin<MixinImplementationA>()
.AddMixin<MixinImplementationB>()
.BuildConfiguration();
MixinConfiguration.SetActiveConfiguration(config);
Unfortunately, you cannot simply call new on the TargetImplementation and expect a mixin. Instead, you have to ask Re-mix to create a TargetImplementation instance so that it can build a new type to your specification and instantiate it. When it is asked for an instance of TargetImplementation, it will return a mixin containing all of the interfaces and classes combined.
ITargetInterface target = ObjectFactory.Create<TargetImplementation>(ParamList.Empty);
target.DoSomething();
var targetAsMixinA = target as IMixinInterfaceA;
if (targetAsMixinA != null)
{
targetAsMixinA.MethodA();
}
var targetAsMixinB = target as IMixinInterfaceB;
if (targetAsMixinB != null)
{
targetAsMixinB.MethodB(30);
}

Using Interface variables

I'm still trying to get a better understanding of Interfaces. I know about what they are and how to implement them in classes.
What I don't understand is when you create a variable that is of one of your Interface types:
IMyInterface somevariable;
Why would you do this? I don't understand how IMyInterface can be used like a class...for example to call methods, so:
somevariable.CallSomeMethod();
Why would you use an IMyInterface variable to do this?
You are not creating an instance of the interface - you are creating an instance of something that implements the interface.
The point of the interface is that it guarantees that what ever implements it will provide the methods declared within it.
So now, using your example, you could have:
MyNiftyClass : IMyInterface
{
public void CallSomeMethod()
{
//Do something nifty
}
}
MyOddClass : IMyInterface
{
public void CallSomeMethod()
{
//Do something odd
}
}
And now you have:
IMyInterface nifty = new MyNiftyClass()
IMyInterface odd = new MyOddClass()
Calling the CallSomeMethod method will now do either something nifty or something odd, and this becomes particulary useful when you are passing in using IMyInterface as the type.
public void ThisMethodShowsHowItWorks(IMyInterface someObject)
{
someObject.CallSomeMethod();
}
Now, depending on whether you call the above method with a nifty or an odd class, you get different behaviour.
public void AnotherClass()
{
IMyInterface nifty = new MyNiftyClass()
IMyInterface odd = new MyOddClass()
// Pass in the nifty class to do something nifty
this.ThisMethodShowsHowItWorks(nifty);
// Pass in the odd class to do something odd
this.ThisMethodShowsHowItWorks(odd);
}
EDIT
This addresses what I think your intended question is - Why would you declare a variable to be of an interface type?
That is, why use:
IMyInterface foo = new MyConcreteClass();
in preference to:
MyConcreteClass foo = new MyConcreteClass();
Hopefully it is clear why you would use the interface when declaring a method signature, but that leaves the question about locally scoped variables:
public void AMethod()
{
// Why use this?
IMyInterface foo = new MyConcreteClass();
// Why not use this?
MyConcreteClass bar = new MyConcreteClass();
}
Usually there is no technical reason why the interface is preferred. I usually use the interface because:
I typically inject dependencies so the polymorphism is needed
Using the interface clearly states my intent to only use members of the interface
The one place where you would technically need the interface is where you are utilising the polymorphism, such as creating your variable using a factory or (as I say above) using dependency injection.
Borrowing an example from itowlson, using concrete declaration you could not do this:
public void AMethod(string input)
{
IMyInterface foo;
if (input == "nifty")
{
foo = new MyNiftyClass();
}
else
{
foo = new MyOddClass();
}
foo.CallSomeMethod();
}
Because this:
public void ReadItemsList(List<string> items);
public void ReadItemsArray(string[] items);
can become this:
public void ReadItems(IEnumerable<string> items);
Edit
Think of it like this:
You have to be able to do this.
rather than:
You have to be this.
Essentially this is a contract between the method and it's callers.
Using interface variables is the ONLY way to allow handler methods to be written which can accept data from objects that have different base classes.
This is about as clear as anyone is going to get.
An interface is used so you do not need to worry about what class implements the interface. An example of this being useful is when you have a factory method that returns a concrete implementation that may be different depending on the environment you are running in. It also allows an API designer to define the API while allowing 3rd parties to implement the API in any way they see fit. Sun does this with it's cryptographic API's for Java.
public interface Foo {
}
public class FooFactory {
public static Foo getInstance() {
if(os == 'Windows') return new WinFoo();
else if(os == 'OS X') return new MacFoo();
else return new GenricFoo();
}
}
Your code that uses the factory only needs to know about Foo, not any of the specific implementations.
I was in same position and took me few days to figure out why do we have to use interface variable.
IDepartments rep = new DepartmentsImpl();
why not
DepartmentsImpl rep = new DepartmentsImpl();
Imagine If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation.
class Test
{
static void Main()
{
SampleClass sc = new SampleClass();
IControl ctrl = (IControl)sc;
ISurface srfc = (ISurface)sc;
// The following lines all call the same method.
sc.Paint();
ctrl.Paint();
srfc.Paint();
}
}
interface IControl
{
void Paint();
}
interface ISurface
{
void Paint();
}
class SampleClass : IControl, ISurface
{
// Both ISurface.Paint and IControl.Paint call this method.
public void Paint()
{
Console.WriteLine("Paint method in SampleClass");
}
}
// Output:
// Paint method in SampleClass
// Paint method in SampleClass
// Paint method in SampleClass
If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces.
public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}
The class member IControl.Paint is only available through the IControl interface, and ISurface.Paint is only available through ISurface. Both method implementations are separate, and neither is available directly on the class. For example:
IControl c = new SampleClass();
ISurface s = new SampleClass();
s.Paint();
Please do correct me if i am wrong as i am still learning this Interface concept.
Lets say you have class Boat, Car, Truck, Plane.
These all share a common method TakeMeThere(string destination)
You would have an interface:
public interface ITransportation
{
public void TakeMeThere(string destination);
}
then your class:
public class Boat : ITransportation
{
public void TakeMeThere(string destination) // From ITransportation
{
Console.WriteLine("Going to " + destination);
}
}
What you're saying here, is that my class Boat will do everything ITransportation has told me too.
And then when you want to make software for a transport company. You could have a method
Void ProvideServiceForClient(ITransportation transportationMethod, string whereTheyWantToGo)
{
transportationMethod.TakeMeThere(whereTheyWantToGo); // Cause ITransportation has this method
}
So it doesn't matter which type of transportation they want, because we know it can TakeMeThere
This is not specific to C#,so i recommend to move to some othere flag.
for your question,
the main reason why we opt for interface is to provide a protocol between two components(can be a dll,jar or any othere component).
Please refer below
public class TestClass
{
static void Main()
{
IMyInterface ob1, obj2;
ob1 = getIMyInterfaceObj();
obj2 = getIMyInterfaceObj();
Console.WriteLine(ob1.CallSomeMethod());
Console.WriteLine(obj2.CallSomeMethod());
Console.ReadLine();
}
private static bool isfirstTime = true;
private static IMyInterface getIMyInterfaceObj()
{
if (isfirstTime)
{
isfirstTime = false;
return new ImplementingClass1();
}
else
{
return new ImplementingClass2();
}
}
}
public class ImplementingClass1 : IMyInterface
{
public ImplementingClass1()
{
}
#region IMyInterface Members
public bool CallSomeMethod()
{
return true;
}
#endregion
}
public class ImplementingClass2 : IMyInterface
{
public ImplementingClass2()
{
}
#region IMyInterface Members
public bool CallSomeMethod()
{
return false;
}
#endregion
}
public interface IMyInterface
{
bool CallSomeMethod();
}
Here the main method does not know about the classes still it is able to get different behaviour using the interface.
The purpose of the Interface is to define a contract between several objects, independent of specific implementation.
So you would usually use it when you have an Intrace ISomething, and a specific implementation
class Something : ISomething
So the Interface varialbe would come to use when you instantiate a contract:
ISomething myObj = new Something();
myObj.SomeFunc();
You should also read interface C#
Update:
I will explaing the logic of using an Interface for the variable and not the class itself by a (real life) example:
I have a generic repositor interace:
Interface IRepository {
void Create();
void Update();
}
And i have 2 seperate implementations:
class RepositoryFile : interface IRepository {}
class RepositoryDB : interface IRepository {}
Each class has an entirely different internal implementation.
Now i have another object, a Logger, that uses an already instansiated repository to do his writing. This object, doesn't care how the Repository is implemented, so he just implements:
void WriteLog(string Log, IRepository oRep);
BTW, this can also be implemented by using standard classes inheritance. But the difference between using interfaces and classes inheritance is another discussion.
For a slightly more details discussion on the difference between abstract classes and interfaces see here.
Say, for example, you have two classes: Book and Newspaper. You can read each of these, but it wouldn't really make sense for these two to inherit from a common superclass. So they will both implement the IReadable interface:
public interface IReadable
{
public void Read();
}
Now say you're writing an application that will read books and newspapers for the user. The user can select a book or newspaper from a list, and that item will be read to the user.
The method in your application that reads to the user will take this Book or Newspaper as a parameter. This might look like this in code:
public static void ReadItem(IReadable item)
{
item.Read();
}
Since the parameter is an IReadable, we know that the object has the method Read(), thus we call it to read it to the user. It doesn't matter whether this is a Book, Newspaper, or anything else that implements IReadable. The individual classes implement exactly how each item will be read by implementing the Read() method, since it will most likely be different for the different classes.
Book's Read() might look like this:
public void Read()
{
this.Open();
this.TurnToPage(1);
while(!this.AtLastPage)
{
ReadText(this.CurrentPage.Text);
this.TurnPage();
}
this.Close();
}
Newspaper's Read() would likely be a little different:
public void Read()
{
while(!this.OnBackPage)
{
foreach(Article article in this.CurrentPage.Articles)
{
ReadText(article.Text);
}
}
}
The point is that the object contained by a variable that is an interface type is guaranteed to have a specific set of methods on it, even if the possible classes of the object are not related in any other way. This allows you to write code that will apply to a variety of classes that have common operations that can be performed on them.
No, it is not possible. Designers did not provide a way. Of course, it is of common sense also. Because interface contains only abstract methods and as abstract methods do not have a body (of implementation code), we cannot create an object..
Suppose even if it is permitted, what is the use. Calling the abstract method with object does not yield any purpose as no output. No functionality to abstract methods.
Then, what is the use of interfaces in Java design and coding. They can be used as prototypes from which you can develop new classes easily. They work like templates for other classes that implement interface just like a blue print to construct a building.
I believe everyone is answering the polymorphic reason for using an interface and David Hall touches on partially why you would reference it as an interface instead of the actual object name. Of course, being limited to the interface members etc is helpful but the another answer is dependency injection / instantiation.
When you engineer your application it is typically cleaner, easier to manage, and more flexible if you do so utilizing dependency injection. It feels backwards at first if you've never done it but when you start backtracking you'll wish you had.
Dependency injection normally works by allowing a class to instantiate and control the dependencies and you just rely on the interface of the object you need.
Example:
Layer the application first. Tier 1 logic, tier 2 interface, tier 3 dependency injection. (Everyone has their own way, this is just for show).
In the logic layer you reference the interfaces and dependency layer and then finally you create logic based on only the interfaces of foreign objects.
Here we go:
public IEmployee GetEmployee(string id)
{
IEmployee emp = di.GetInstance<List<IEmployee>>().Where(e => e.Id == id).FirstOrDefault();
emp?.LastAccessTimeStamp = DateTime.Now;
return emp;
}
Notice above how we use di.GetInstance to get an object from our dependency. Our code in that tier will never know or care about the Employee object. In fact if it changes in other code it will never affect us here. If the interface of IEmployee changes then we may need to make code changes.
The point is, IEmployee emp = never really knows what the actual object is but does know the interface and how to work with it. With that in mind, this is when you want to use an interface as opposed to an object becase we never know or have access to the object.
This is summarized.. Hopefully it helps.
This is a fundamental concept in object-oriented programming -- polymorphism. (wikipedia)
The short answer is that by using the interface in Class A, you can give Class A any implementation of IMyInterface.
This is also a form of loose coupling (wikipedia) -- where you have many classes, but they do not rely explicitly on one another -- only on an abstract notion of the set of properties and methods that they provide (the interface).

Categories

Resources