Is it Possible to Force Properties Generated by Entity Framework to implement Interfaces? - vb.net

Example Interface:
public Interface IEntity
Property ID() as Integer
end Interface
I want all my EF objects to implement this interface on there Primary Keys.
Is this possible?

This seems very easy to do in CSharp but in VB you have to specifically declare which Properties/Functions/Subs are Implementing the Interface:
public Property Id() as Integer Implements IEntity.Id
Unfortunately I had to Rip out the designer file and modify the generated properties. I ended up getting rid of the Generated File all together and now keep my Models in separate classes with all of the Attribute mappings.

Yes, you can. The classes that the designer generates are declared partial. In a seperate source file you can declare additional methods for these classes. You can also declare specific interfaces that are already implemented by the generated class.
/* This is the interface that you want to have implemented. */
public interface ISomething
{
void DoSomething();
}
/* This would be part of the generated class */
partial class PartialClass
{
public void DoSomething()
{
}
}
/* This would be your own extension */
partial class PartialClass : ISomething
{
}

The classes are partial, so it should be very easy to do.

Related

DDD ValueObject and Enumeration , is there any good way to implement serialization?

In DDD, Value Object and Enumeration are quite beautiful so that I want use both two in the daily program logic, not only domain logic. When use customized value objects and enumerations, serialization problem is coming : should I implemented all the value objects and enumeration with System.Text.Json.JsonConverter<T> , or is there any good way to handle serialization and deserialization ?
Update:
to make it clear, Eumeration demo as below(ValueObject derived classes are same.):
[JsonConverter(typeof(CustomizedConverter))]
public class CustomizedEnumeration1 : Enumeration
{
public string Customized { get; protected set; }
public ... // some other customized property or class
public CustomizedEnumeration(int id, string name, string customized) : base(id, string) {
Customized = customized;
}
}
public class Customized2 : Enumeration
{ ... }
public class OtherCustomized: Enumeration
{ ... }
In DDD, properties sometimes are sealed by protected/private setter, deserialization has no right to set the value. Many derived classes can't deserialize as expected, so we have to rewrite serialization with System.Text.Json.JsonConverter<T> one by one. rewrite every derived Enumeration / Valueobject converter is not good, can any one point out any easy abstraction for that ?
You can achieve your desired result. You need to switch to NewtonsoftJson serialization.
Call this in Startup.cs in the ConfigureServices method:
services.AddControllers().AddNewtonsoftJson();
After this, your constructor will be called by deserialization for classes with private setter.
There is no need for custom converters.
For reference, I am using ASP Net Core 3.1

Do we need interfaces for dependency injection?

I have an ASP.NET Core application. The application has few helper classes that does some work. Each class has different signature method. I see lot of .net core examples online that create interface for each class and then register types with DI framework. For example
public interface IStorage
{
Task Download(string file);
}
public class Storage
{
public Task Download(string file)
{
}
}
public interface IOcr
{
Task Process();
}
public class Ocr:IOcr
{
public Task Process()
{
}
}
Basically for each interface there is only one class. Then i register these types with DI as
services.AddScoped<IStorage, Storage>();
services.AddScoped<IOcr,Ocr>();
But i can register type without having interfaces so interfaces here look redundant. eg
services.AddScoped<Storage>();
services.AddScoped<Ocr>();
So do i really need interfaces?
No, you don't need interfaces for dependency injection. But dependency injection is much more useful with them!
As you noticed, you can register concrete types with the service collection and ASP.NET Core will inject them into your classes without problems. The benefit you get by injecting them over simply creating instances with new Storage() is service lifetime management (transient vs. scoped vs. singleton).
That's useful, but only part of the power of using DI. As #DavidG pointed out, the big reason why interfaces are so often paired with DI is because of testing. Making your consumer classes depend on interfaces (abstractions) instead of other concrete classes makes them much easier to test.
For example, you could create a MockStorage that implements IStorage for use during testing, and your consumer class shouldn't be able to tell the difference. Or, you can use a mocking framework to easily create a mocked IStorage on the fly. Doing the same thing with concrete classes is much harder. Interfaces make it easy to replace implementations without changing the abstraction.
Does it work? Yes. Should you do it? No.
Dependency Injection is a tool for the principle of Dependency Inversion : https://en.wikipedia.org/wiki/Dependency_inversion_principle
Or as it's described in SOLID
one should “depend upon abstractions, [not] concretions."
You can just inject concrete classes all over the place and it will work. But it's not what DI was designed to achieve.
No, we don't need interfaces. In addition to injecting classes or interfaces you can also inject delegates. It's comparable to injecting an interface with one method.
Example:
public delegate int DoMathFunction(int value1, int value2);
public class DependsOnMathFunction
{
private readonly DoMathFunction _doMath;
public DependsOnAFunction(DoMathFunction doMath)
{
_doMath = doMath;
}
public int DoSomethingWithNumbers(int number1, int number2)
{
return _doMath(number1, number2);
}
}
You could do it without declaring a delegate, just injecting a Func<Something, Whatever> and that will also work. I'd lean toward the delegate because it's easier to set up DI. You might have two delegates with the same signature that serve unrelated purposes.
One benefit to this is that it steers the code toward interface segregation. Someone might be tempted to add a method to an interface (and its implementation) because it's already getting injected somewhere so it's convenient.
That means
The interface and implementation gain responsibility they possibly shouldn't have just because it's convenient for someone in the moment.
The class that depends on the interface can also grow in its responsibility but it's harder to identify because the number of its dependencies hasn't grown.
Other classes end up depending on the bloated, less-segregated interface.
I've seen cases where a single dependency eventually grows into what should really be two or three entirely separate classes, all because it was convenient to add to an existing interface and class instead of injecting something new. That in turn helped some classes on their way to becoming 2,500 lines long.
You can't prevent someone doing what they shouldn't. You can't stop someone from just making a class depend on 10 different delegates. But it can set a pattern that guides future growth in the right direction and provides some resistance to growing interfaces and classes out control.
(This doesn't mean don't use interfaces. It means that you have options.)
I won't try to cover what others have already mentioned, using interfaces with DI will often be the best option. But it's worth mentioning that using object inheritance at times may provide another useful option. So for example:
public class Storage
{
public virtual Task Download(string file)
{
}
}
public class DiskStorage: Storage
{
public override Task Download(string file)
{
}
}
and registering it like so:
services.AddScoped<Storage, DiskStorage>();
Without Interface
public class Benefits
{
public void BenefitForTeacher() { }
public void BenefitForStudent() { }
}
public class Teacher : Benefits
{
private readonly Benefits BT;
public Teacher(Benefits _BT)
{ BT = _BT; }
public void TeacherBenefit()
{
base.BenefitForTeacher();
base.BenefitForStudent();
}
}
public class Student : Benefits
{
private readonly Benefits BS;
public Student(Benefits _BS)
{ BS = _BS; }
public void StudentBenefit()
{
base.BenefitForTeacher();
base.BenefitForStudent();
}
}
here you can see benefits for Teachers is accessible in Student class and benefits for Student is accessible in Teacher class which is wrong.
Lets see how can we resolve this problem using interface
With Interface
public interface IBenefitForTeacher
{
void BenefitForTeacher();
}
public interface IBenefitForStudent
{
void BenefitForStudent();
}
public class Benefits : IBenefitForTeacher, IBenefitForStudent
{
public Benefits() { }
public void BenefitForTeacher() { }
public void BenefitForStudent() { }
}
public class Teacher : IBenefitForTeacher
{
private readonly IBenefitForTeacher BT;
public Teacher(IBenefitForTeacher _BT)
{ BT = _BT; }
public void BenefitForTeacher()
{
BT.BenefitForTeacher();
}
}
public class Student : IBenefitForStudent
{
private readonly IBenefitForStudent BS;
public Student(IBenefitForStudent _BS)
{ BS = _BS; }
public void BenefitForStudent()
{
BS.BenefitForStudent();
}
}
Here you can see there is no way to call Teacher benefits in Student class and Student benefits in Teacher class
So interface is used here as an abstraction layer.

VB.NET access level of interface declaration not matching access level of implementation [duplicate]

Interface behaves differently in Vb.Net. Below is a sample code snippet where IStudent interface has a method SayHello which is implemented by a class Student. The Access modifier for SayHello should be Public by default. By changing Access modifier to Private is not breaking the existing code and still i can access this private method using below code
Dim stdnt As IStudent = New Student
stdnt.SayHello()
Access modifier determines the scope of the members in a class, more over private members are accessible only from the class which exists. But here the theory of Access Modifier, Encapsulation are broken.
Why .net has designed in this way?
Is the concept of Access modifier and encapsulation are really broken?
How .net framework internally handle this situation?
Thanks in advance
Module Module1
Sub Main()
Dim stdnt As IStudent = New Student
stdnt.Name = "vimal"
stdnt.SayHello()
End Sub
End Module
Public Interface IStudent
Property Name As String
Sub SayHello()
End Interface
Public Class Student
Implements IStudent
Private Property Name As String Implements IStudent.Name
Private Sub SayHello() Implements IStudent.SayHello
Console.WriteLine("Say Hello!")
End Sub
End Class
The original poster submitted this question to me via TheBugGuys#Coverity.com; my answer is here:
https://communities.coverity.com/blogs/development-testing-blog/2013/10/09/oct-9-posting-interface-behaves-differently-in-visual-basic
To briefly summarize:
Why was .NET designed in this way?
That question is impossibly vague.
Is encapsulation broken by explicit implementation in C# and VB?
No. The privacy of the method restricts the accessibility domain of the methods name, not who can call the method. If the author of the class chooses to make a private method callable by some mechanism other than looking it up by name, that is their choice. A third party cannot make the choice for them except via techniques such as private reflection, which do break encapsulation.
How is this feature implemented in .NET?
There is a special metadata table for explicit interface implementations. The CLR consults it first when attempting to figure out which class (or struct) method is associated with which interface method.
From MSDN:
You can use a private member to implement an interface member. When a private member implements a member of an interface, that member becomes available by way of the interface even though it is not available directly on object variables for the class.
In C#, this behaviour is achieved by implementing the interface explicitly, like this:
public interface IStudent {
string Name { get; set; }
void SayHello();
}
public class Student : IStudent {
string IStudent.Name { get; set; }
void IStudent.SayHello() {
Console.WriteLine("Say Hello!");
}
}
So, if you were to omit the IStudent. in front of the method names, it would break. I see that in the VB syntax the interface name is included. I don't know whether this has any implications altough. But interface members aren't private, since the interface isn't. They're kinda public...
There is no fundamental difference between C# and VB.NET, they just chose different ways to solve ambiguity. Best demonstrated with a C# snippet:
interface ICowboy {
void Draw();
}
interface IPainter {
void Draw();
}
class CowboyPainter : ICowboy, IPainter {
void ICowboy.Draw() { useGun(); }
void IPainter.Draw() { useBrush(); }
// etc...
}
VB.NET just chose consistent interface implementation syntax so the programmer doesn't have to weigh the differences between implicit and explicit implementation syntax. Simply always explicit in VB.NET.
Only the accessibility of the interface method matters. Always public.
When your variable stdnt is declared as IStudent, the interface methods and properties are then made Public, so the derived class' (Student) implementation is executed. If, on the other hand, if stdnt was declared as Student, the private members (Name and SayHello) would not be implemented, and an error would be thrown.
I'm guessing that the Interface members stubs (Name & SayHello) are by default Public, and the access modifier definitions of the derived class' implementation are ignored.
IMHO.
The exact equivalent in C# is the following - the method available to objects of the interface type and the private method available otherwise:
void IStudent.SayHello()
{
this.SayHello();
}
private void SayHello()
{
Console.WriteLine("Say Hello!");
}

Interface behavior is dfferent in VB.Net

Interface behaves differently in Vb.Net. Below is a sample code snippet where IStudent interface has a method SayHello which is implemented by a class Student. The Access modifier for SayHello should be Public by default. By changing Access modifier to Private is not breaking the existing code and still i can access this private method using below code
Dim stdnt As IStudent = New Student
stdnt.SayHello()
Access modifier determines the scope of the members in a class, more over private members are accessible only from the class which exists. But here the theory of Access Modifier, Encapsulation are broken.
Why .net has designed in this way?
Is the concept of Access modifier and encapsulation are really broken?
How .net framework internally handle this situation?
Thanks in advance
Module Module1
Sub Main()
Dim stdnt As IStudent = New Student
stdnt.Name = "vimal"
stdnt.SayHello()
End Sub
End Module
Public Interface IStudent
Property Name As String
Sub SayHello()
End Interface
Public Class Student
Implements IStudent
Private Property Name As String Implements IStudent.Name
Private Sub SayHello() Implements IStudent.SayHello
Console.WriteLine("Say Hello!")
End Sub
End Class
The original poster submitted this question to me via TheBugGuys#Coverity.com; my answer is here:
https://communities.coverity.com/blogs/development-testing-blog/2013/10/09/oct-9-posting-interface-behaves-differently-in-visual-basic
To briefly summarize:
Why was .NET designed in this way?
That question is impossibly vague.
Is encapsulation broken by explicit implementation in C# and VB?
No. The privacy of the method restricts the accessibility domain of the methods name, not who can call the method. If the author of the class chooses to make a private method callable by some mechanism other than looking it up by name, that is their choice. A third party cannot make the choice for them except via techniques such as private reflection, which do break encapsulation.
How is this feature implemented in .NET?
There is a special metadata table for explicit interface implementations. The CLR consults it first when attempting to figure out which class (or struct) method is associated with which interface method.
From MSDN:
You can use a private member to implement an interface member. When a private member implements a member of an interface, that member becomes available by way of the interface even though it is not available directly on object variables for the class.
In C#, this behaviour is achieved by implementing the interface explicitly, like this:
public interface IStudent {
string Name { get; set; }
void SayHello();
}
public class Student : IStudent {
string IStudent.Name { get; set; }
void IStudent.SayHello() {
Console.WriteLine("Say Hello!");
}
}
So, if you were to omit the IStudent. in front of the method names, it would break. I see that in the VB syntax the interface name is included. I don't know whether this has any implications altough. But interface members aren't private, since the interface isn't. They're kinda public...
There is no fundamental difference between C# and VB.NET, they just chose different ways to solve ambiguity. Best demonstrated with a C# snippet:
interface ICowboy {
void Draw();
}
interface IPainter {
void Draw();
}
class CowboyPainter : ICowboy, IPainter {
void ICowboy.Draw() { useGun(); }
void IPainter.Draw() { useBrush(); }
// etc...
}
VB.NET just chose consistent interface implementation syntax so the programmer doesn't have to weigh the differences between implicit and explicit implementation syntax. Simply always explicit in VB.NET.
Only the accessibility of the interface method matters. Always public.
When your variable stdnt is declared as IStudent, the interface methods and properties are then made Public, so the derived class' (Student) implementation is executed. If, on the other hand, if stdnt was declared as Student, the private members (Name and SayHello) would not be implemented, and an error would be thrown.
I'm guessing that the Interface members stubs (Name & SayHello) are by default Public, and the access modifier definitions of the derived class' implementation are ignored.
IMHO.
The exact equivalent in C# is the following - the method available to objects of the interface type and the private method available otherwise:
void IStudent.SayHello()
{
this.SayHello();
}
private void SayHello()
{
Console.WriteLine("Say Hello!");
}

In Object oriented programming when do we need abstraction?

I read many posts about the "Interface" and "Abstract Class"
Basically, we use "Abstract Class" when we talking about the characteristic of the Object.
And we use "Interface" when we taling about what the object capable can do.
But it still confuse so I make up an example for myself to practice.
so now I thinking of a Object 'Cargo;
public abstract class cargo {
protected int id;
public abstract int getWidth(int width);
public abstract int setWidth(int width);
public abstract int setHeight(int h);
public abstract int getHeight(int h);
public abstract int setDepth(int d);
public abstract int getDepth(int d);
public abstract int volume(int w,int h,int d);
public int getId(){
return this.id;
}
public abstract int setId();
public abstract void setBrand();
public abstract void getBrand( );
.....so on , still have a lot of characteristic of a cargo
}
//in the other class
public class usaCargo extends cargo{
....
private
}
So here is few Question about my design.
1.So in the real programming project world, are we actually doing like above? for me i think it's ok design, we meet the basic characteristic of cargo.
if we setup "private id" , then we actually can't use "id" this variable in any subclass because it's private, so is that mean every variable we defined in abstract class must be either public/ protected?
can someone give some suitable example so my cargo can implement some interface?
public interface registration{
public void lastWarrantyCheck();
}
But seems not suitable here...
we dont usually define variable inside interface, do we ??
I try to gain more sense on OOP . Forgive my long questions.
You would define variables in the Abstract class so that methods defined in the abstract class have variables to use. The scope of those variables depend on how you want concrete classes to access those variables:
private should be used when you want to force a concrete class to go through a getter or setter defined in the abstract class.
protected should be used when you want to give the concrete class direct access to the variable.
public should be used when you want the variable to be accessible by any class.
A reasonable interface that a Cargo object might implement could be Shippable as in how to move the cargo from a source to a destination. Some cargo may be shipped via freight train, some might be shippable by airplane, etc. It is up to the concrete class to implement Shippable and define just how that type of cargo would be shipped.
public interface Shippable {
public void ship();
}
Lastly a variable defined in an interface must be public static and final meaning it would be a constant variable.
Hope this clears it up for you!
Abstract classes can contain implementation, so they can have private variables and methods. Interfaces on the other hand cannot.
You can find some examples on how to implement interfaces here. However, I included how you would implement your registration example below.
public class Cargo implements Registration{
public void lastWarrantyCheck(){
System.out.println("Last warranty check");
}
}
Interface variables are possible, but they should only include constant declarations (variable declarations that are declared to be both static and final). More information about this can be found here.
Variables in an abstract class may be declared as protected, and they will only be available within it and any extending classes. Private variables are never accessible inside extending classes.
Interfaces provide a list of functions that are required by the classes that implement them. For example, you might use an interface hasWarranty to define all the functions that an object would need to handle warranty-related activities.
public interface hasWarranty {
public void lastWarrantyCheck();
public void checkWarranty();
}
Then, any objects that need to perform warranty-related activities should implement that interface:
// Disclaimer: been away from Java for a long time, so please interpret as pseudo-code.
// Will compile
public class Car implements hasWarranty {
public void lastWarrantyCheck() {
... need to have this exact function or program won't compile ...
}
public void checkWarranty() {
... need to have this exact function or program won't compile ...
}
}
// Missing one of the required functions defined in hasWarranty
public class Bus implements hasWarranty {
public void lastWarrantyCheck() {
... need to have this exact function or program won't compile ...
}
}
Only constants, really, as variables declared in an interface are immutable and are shared by all objects that implement that interface. They are implicitly "static final".