Add reference Error in c# console app - c#

I am creating a Console App in C# using VS2010. It is based in 3-Layer Architecture containing three layers
PMS.UI
PMS.DAL
PMS.BL
To remove Circular Dependency between PMS.DAL and PMS.BL I added an extra layer PMS.Service.
I created a Vehicle class in PMS.BL which implements interface IVehicle from PMS.Service.
I added reference of PMS.Service in both DAL and BL.
Now UI calls AddNewVehicle() method of Vehicle class of BL which implements IVehicle
BL calls AddNewVehicle(IVehicle obj) method of VehicleDao in PMS.DAL...
All working fine but at time of build Compiler says to add reference of PMS.Service in PMS.UI.
PMS.UI doesn't implement any interface of PMS.Service but calls AddNewVehicle() method of Vehicle class of PMS.BL which implements IVehicle.
Is it necessary to add reference of PMS.Service to PMS.UI only if it creates instance of Vehicle Class of PMS.BL which implements IVehicle present in PMS.Service..
Please help me I am new to use Interface in c#...
Thankyou Guys for your answers but i am still confused. I will present my code here.I have added all four layers as different c sharp class library(different layers).
1)PMS.UI(Added reference of PMS.BL)
Program.cs
using System;
using PMS.BL;
namespace PMS.APP
{
class Program
{
static void Main()
{
var vBo = new VehicleBo();//Compiler Says Add reference of PMS.Service here.Why is it necessary to add Reference of it??
vbo.VehicleNumber = "BA1PA 1212";
vbo.VehicleType = "Bike";
vbo.SaveNewVehicle();
}
}
}
2)PMS.BL(Added reference of PMS.DAL and PMS.Service)
VehicleBO.cs
using PMS.DAL;
using PMS.Service;
namespace PMS.BL
{
public class VehicleBo : IVehicle
{
public string VehicleNumber { get; set; }
public string VehicleType { get; set; }
public void SaveNewVehicle()
{
var vDao = new VehicleDao();
vDao.SaveNewVehicle(this);
}
}
}
3)PMS.DAL(Added reference of PMS.Service)
using PMS.Service;
namespace PMS.DAL
{
public class VehicleDao
{
public void SaveNewVehicle(IVehicle obj)
{
//code to insert in database
}
}
}
4)PMS.Service
IVehicle.cs
namespace PMS.Service
{
public interface IVehicle
{
string VehicleNumber { get; set; }
string VehicleType { get; set; }
void SaveNewVehicle();
}
}

With the given details (and no code). This is what I understand.
PMS.Service (IVehicle.cs)
PMS.BL (Vehicle : IVehicle)
In this scenario, if you are exposing Vehicle, you will have to add reference to PMS.Service also. In any case, having model interfaces/contact in service implementation does not look right. I would rather consider creating PMS.Contracts and have my model/service contracts there.
Hope that helps.

I think that you have an architecture problem. Basically, if you are in three layer, this is the good way :
IHM => BLL => DAL
Core
Core is a project contains tools function (format date, number etc.) and your interface.
The dependencies : IHM reference BLL / BLL reference DAL. An all of these reference Core. Core have no dependency.
I'm beginner like you with interface. Here the way i'll choose if i have to do it :
4 projects :
Core
BLL (depecencies DAL - Core)
DAL (depecencies Core)
IHM (depecencies BLL - Core)
In Core : Two things : An Interface IVehicle and a class that implement this class call Vehicle
Because we need to use a DAL, i don't know how to do for not use Core.Vehicle. An abstract class is not good because if DAL need to return a "IVehicule" object, we need to implement an object and we can't implement an Abstract or Interface.
In BLL : Two objects : Car and Truck that implement Core.Vehicule
In DAL : One object : Vehicule with a method for return a Core.Vehicule
In IHM : A call of BLL.Car
And it's doing the thing...
EDIT :
I've post a question like yours : POO and Interface (in C#)
Hope it help you.

Related

Execute code in a class library when you do not have a reference to that class library

Say I have a class library like this:
using ClassLibrary2;
namespace ClassLibrary1
{
public class Class1 : IClass1
{
public string SayHello()
{
return "Hello";
}
}
}
and a class library like this:
namespace ClassLibrary2
{
public interface IClass1
{
string SayHello();
}
public class Class3
{
IClass1 _class1;
public Class3(IClass1 class1)
{
_class1 = class1;
string test = _class1.SayHello();
}
}
}
and a program like this:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
IClass1 class1 = new Class1();
Class3 class3 = new Class3(class1);
}
}
}
ClassLibrary1 references ClassLibrary2. WindowsFormsApplication1 references ClassLibrary1 and ClassLibrary2.
The program finishes. ClassLibrary2 is able to execute code from ClassLibrary1 even though ClassLibrary2 does not reference ClassLibrary1. What is this technique called? I want to read more about it and use it. I realise it is polymorphism. I am referring to the technique of executing code in a class library without a dependancy.
You discovered the D in SOLID: Dependency inversion principle.
Program against interfaces, not implementations.
You are not executing code from ClassLibrary1 in ClassLibrary2, you are invoking functionality described in an interface that you defined in ClassLibrary2 itself.
At runtime, the implementation of what you invoke may be provided by ClassLibrary12635.
One example where this can be really useful is if I define an interface for, say, a DAL (Data access layer) component in a separate library, defining the functionality of that DAL component. I can implement business logic in a business logic layer (BLL) using that interface (I need to reference the library with the interface).
For my DAL itself I can implement different implementations, and create two different libraries - for instance one that uses local, client side storage, and another that uses a centralised database. I can then substitute one DAL library for the other without having to change a single line of code in my business logic.

How to reuse code for singleton object in C#

I got trouble when design class for my project. Currently, we developed 2 projects with the same structure but have some differences inside.
At project A, I have class ACore that includes class AConfiguration, AEquipmentManager. And I made an instance for object ACore that at everywhere in project, i can use: Acore.AConfiguration.XYZ (XYZ is method or property of AConfiguration class) or ACore.AEquipmentmanager.ABC(ABC is method or property of AEquipmentManager class)
At project B, I still have same structure with project A (BCore, BConfiguration, BEquipmentManager). But BConfiguration has different with AConfiguration (because each project has different configuration) and BEquipmentManager also has different with AEquipmentManager.
I want to reuse code for class ACore and BCore because they have the same code (Initialize EquipmentManager, Initialize Configuration, Dispose EquipmentManager, Dispose Configuration,...). Now, I want to write a library BaseCore that have the same structure with ACore and BCore (there are 2 class Configuration, EquipmentManager, same Intialize function, Dispose function), and with specific project (like A project, B project, or even C, D project later) i can use BaseCore library class (for reuse code) and just implement XEquipmentManager, XCofiguration depend on each project.
What is the best way I should design in this case? Thank for sharing your idea.
Regards,
Hoa Nguyen
I think you're on the right track,
But I would do it with interfaces:
Implement Core class that uses class that implements IConfigurable.
Make sure AConfiguration implements IConfigurable and all the
relevant methods.
Alternativly you can do something like that:
Implement Core class that uses Configuration class.
Implement AConfiguration/BConfiguration that inherits from
Configuration.
Reference A and B to the same Core class and that's it.
Hope it helps.
Does AConfiguration and BConfiguration have the same set of methods with different implementations or do the set methods also differ? If the set of methods are the same you could do it with interfaces. You could define an interface for configuration and equipmentamanager. Then you just BaseCore using these interface. Then you can supply the specific implementation in the construction of BaseCore Something like this (leaving out the singleton stuff)
interface IConfiguration
{
void somefunc();
}
interface IEquipmentManager
{
void someOtherFunc();
}
class BaseCore
{
private IConfiguration conf;
private IEquipmentmanager eq;
private BaseCore(){};
public BaseCore(IConfiguration inConf, IEquipmentmanager inEq) :
conf(inConf), eq(inEq)
{
conf.someFunc();
}
}
class AConfiguration : IConfiguration
{
public void someFunc()
{
do stuff!
}
public int intprop{get;set;}
}
class AEquipmentmanager : IEquipmentmanager
{
public void someOtherFunc()
{
do stuff!
}
}
Note you have to initialize an instance of AConfiguration and AEquipmentmanager. Before the construction of BaseCore like so
AConfiguration conf = new AConfiguration();
AEquipmentmanager eq = new AEquipmentmanager();
BaseCore base = new BaseCore(conf eq);
Alternatively you can simply create a BaseCore constructor that takes some enum to signify which implementation to you and then initialize an instance of the appropriate class in the BaseCore Constructor.
Alternatively you could possibly to it by implementing BaseCore with to Generic parameters and provide the the configuration and equipmentmanager implementation through these. You could still use the interfaces just the same but implement BaseCore with limits on the Generic arguments. BaseCore would look something like this:
class BaseCore<Configuration_type,Equipmentmanager_type>
where Configuration_type : IConfiguration, new()
where Equipmentmanager_type : IEquipmentmanager, new()
{
public Configuration_type Configuration {get;};
public Equipmentmanager_type Equipmentmanager {get;};
BaseCore()
{
Configuration = new Configuration_type();
Equipmentmanager = new Equipmentmanager_type();
}
}
This however puts the constraint on the types that they need a parameterless constructor. Initialization could supposedly be done afterwards though.
If you want to specialize your core for a specific configuration you can inherit from it like this
class Acore<Configuration_type,Equipmentmanager_type> :
BaseCore<Configuration_type,Equipmentmanager_type>
where Configuration_type : AConfiguration ,new()
where Equipmentmanager_type : AEquipmentmanager, new()
{
Acore() : base()
{
Configuration.intprop = 10;
}
}
Note that i added a property on AConfiguration that is not accessible in BaseCore but is in ACore

Generic DAL / BLL Classes

I'm currently building the Data Access Layer and Business Logic Layer classes for our new application, and I have a question (obviously). First, here are some details that may help:
Using Entity Framework 5 for Model classes and data access
Each "layer" is separated in different class libraries and namespaces (i.e App.Model, App.DAL, App.BLL)
Starting with the DAL - I decided to write a base class for all DAL classes to inherit.
public abstract class DALBase<T> : IDisposable
{
protected AppEntities context;
protected DbSet set;
public DALBase()
{
context = new OECCORPEntities();
set = context.Set(typeof(T));
}
protected virtual void Save()
{
context.SaveChanges();
}
public virtual void Add(T model)
{
set.Add(model);
Save();
}
public virtual T Get(int id)
{
return (T)set.Find(id);
}
public virtual List<T> GetAll()
{
return set.OfType<T>().ToList();
}
public virtual void Delete(int id)
{
T obj = Get(id);
set.Remove(obj);
Save();
}
public virtual void Update()
{
Save();
}
public void Dispose()
{
context.Dispose();
}
}
As you will see, the base class implements a generic type which should be the type of the model the DAL class is responsible for working with. Using the generic type, in the constructor it creates a DbSet using the type of the generic argument - which is used in the predefined CRUD-like virtual functions below (add, get, etc).
And then I got the idea - wait a minute... since it's generic, I really don't have to implement DAL classes for every single model. I can just write something like this:
public class GenericDAL<T> : DALBase<T>
{
public GenericDAL() : base() {}
}
... that I can use for any of the models. OK, so on to the Business Logic Layer. I created a base class for BLL as well:
public abstract class BLLBase<T>
{
protected GenericDAL<T> dal;
public BLLBase()
{
dal = new GenericDAL<T>();
}
public virtual void Add(T model)
{
dal.Add(model);
}
public virtual T Get(int id)
{
return dal.Get(id);
}
public virtual List<T> GetAll()
{
return dal.GetAll();
}
public virtual void Delete(int id)
{
dal.Delete(id);
}
public virtual void Update()
{
dal.Update();
}
}
... which uses the GenericDAL to do its work. So in a simular fashion, I just wrote a GenericBLL class that looks like this:
public class GenericBLL<T> : BLLBase<T>
{
public GenericBLL() : base() { }
}
And to test it, a simple console application:
class Program
{
static void Main(string[] args)
{
GenericBLL<ADMIN> bll = new GenericBLL<ADMIN>();
List<ADMIN> admins = bll.GetAll();
}
}
... where "ADMIN" is the model type. Works like a charm.
The idea behind this was to avoid having to write DAL / BLL classes for every single model, unless it needed extra functionality. Can someone tell me why I WOULDN'T want to do it this way? I think the generic DAL / BLL classes would get the job done and also save development time.
Thank you for your time.
Well, one drawback is that if you decide to add some business rules later on you would have to switch the type from GenericBLL[Whatever] to WhateverBLL.
An obvious solution to this is to create a class that inherits from GenericBLL[Whatever]. Like:
public class WhateverBLL : GenericBLL<Whatever>
and use this class instead.
Right now, your BLL isn't particularly adding value. Every call is simply a pass-through to another layer. Maybe it's the simplicity of your application (and thank your lucky stars that you are so lucky), or maybe you have what I would classify as the actual business logic living elsewhere.
Business logic to me is everything that is done up to the point of persisting data, everything that is done after retrieving data, and things like that. The decisions, the forks in the road, the actions that are taken. Actually saving and retrieving data is typical extremely trivial by comparison.
So as I look at your generic DAL base class, I think it's a fine start. I would probably extract an interface from it so I could replace it when testing. For now, your class that inherits the base isn't adding any value. Do not create layers and classes simply for the sake of it, be sure it adds value and makes your life easier in some way.
As I look at your generic BLL class, I think you probably have your real business logic tucked away in the codebehind on some form, or inside a class file in a console app. While it's certainly possible that there could be generically applicable functionality that only varies on the type, I don't think one class is where you want to be. My suggestion here is to reconsider what you think is your actual business logic. A simple pass-through layer to the DAL probably isn't it.

IOC/DI with 2 classes that implement same interface

I am getting confused with the scenario of 2 classes implementing the same interface and Dependency Injection.
public interface ISomething
{
void DoSomething();
}
public class SomethingA : ISomething
{
public void DoSomething()
{
}
}
public class SomethingAB : ISomething
{
public void DoSomething()
{
}
}
public class Different
{
private ISomething ThisSomething;
public Different(ISomething Something)
{
ThisSomething = Something;
}
}
I have seen online examples say that this is valid but you would only use one class at a time. So if the app is running at SiteA you tell your IOC to use SomethingA but if its at SiteB you tell it to use SomethingAB.
Is it considered bad practice therefore to have one app that has 2 classes that implement 1 interface and for it to try to use both classes? If its not how do you tell the IOC which class to use in the relevant circumstance?
UPDATE: To explain it better I will use Ninject's example:
public class Samurai
{
private IWeapon Weapon;
public Samurai(IWeapon weapon)
{
this.Weapon = weapon;
}
}
public class Sword : IWeapon
{
...
}
public class Gun : IWeapon
{
...
}
public class WarriorModule : NinjectModule
{
public override void Load()
{
this.Bind<IWeapon>().To<Sword>();
this.Bind<IWeapon>().To<Gun>(); //Just an example
}
}
So now you have 2 classes that use IWeapon. Depending on something or a context in your app you want Samurai to have a Sword sometimes or a Gun at other points. How do you make this happen? How do you handle that "if" scenario??
I don't think that this is a bad practice in the general case. There are situations where you could need different implementations of the same interface inside the same application and based on the context use one or another implementation
As far as how to configure your DI to enable this scenario, well, it will depend on your DI of course :-) Some might not support it, others might not, others might partially support it, etc..
For example with Ninject, you could have the following classes:
public interface ISomething
{
}
public class SomethingA : ISomething
{
}
public class SomethingB : ISomething
{
}
public class Foo
{
public Foo(ISomething something)
{
Console.WriteLine(something);
}
}
public class Bar
{
public Bar(ISomething something)
{
Console.WriteLine(something);
}
}
and then use named bindings when configuring the kernel:
// We create the kernel that will be used to provide instances when required
var kernel = new StandardKernel();
// Declare 2 named implementations of the same interface
kernel.Bind<ISomething>().To<SomethingA>().Named("somethingA");
kernel.Bind<ISomething>().To<SomethingB>().Named("somethingB");
// inject SomethingA into Foo's constructor
kernel.Bind<Foo>().ToSelf().WithConstructorArgument(
"something", ctx => ctx.Kernel.Get<ISomething>("somethingA")
);
// inject SomethingB into Bar's constructor
kernel.Bind<Bar>().ToSelf().WithConstructorArgument(
"something", ctx => ctx.Kernel.Get<ISomething>("somethingB")
);
Now when you request an instance of Foo it will inject SomethingA into it its constructor and when you request an instance of Bar it will inject SomethingB into it:
var foo = kernel.Get<Foo>();
var bar = kernel.Get<Bar>();
i worked with Unity and spring in this context and i think that interest lies in having a weak coupling between packages, ie classes, the ability to change service or point of entry is a consequence of the ioc.
ioc provides flexibility in the use of service, or from the time the services implement the same interface,
If Utilize Service A Service B and Service is in the service package A and package B is in B.
Package A has no reference on the package b, but the service A has a reference on the package containing the interfaces.
Therefore we conclude that we have a weak coupling between package A and package b.
Having multiple implementations mapped to the same interface isn't really bad practice, but it isn't he most common usage pattern.
You didn't specify a specific DI tool, but if you use Unity, you can do this with named instances. See here: Unity - how to use multiple mappings for the same type and inject into an object

How to make a unit test mock of an object with non-virtual functions [duplicate]

This question already has answers here:
How to mock non virtual methods?
(8 answers)
Closed last year.
I have a C# class that gets generated using the wsdl.exe tool that looks something like this:
public partial class SoapApi : System.Web.Services.Protocols.SoapHttpClientProtocol
{
public SOAPTypeEnum AskServerQuestion()
{
object[] results = return this.Invoke("AskServerQuestion");
return (SOAPTypeEnum) results[0];
}
}
I have some thin wrapper code around this that keeps track of the result, etc. Is it possible to use any of the object mocking frameworks to make a fake SoapApi class and return predictable results for each of the calls to the thin wrapper functions?
I can't make the AskServerQuestion() function virtual because it's auto-generated by the wsdl.exe tool.
The way I've accomplished this was to inject an ISoapApi instead, where the ISoapApi interface mimics the automatically generated SOAP API.
For your case:
public interface ISoapApi
{
SOAPTypeEnum AskServerQuestion ();
}
Then, take advantage of the fact that the generated SoapApi class is partial, and add this in another file:
public partial class SoapApi : ISoapApi
{
}
Then, consumers should just take an ISoapApi dependency that can be mocked by any of the mocking frameworks.
One downside is, of course, when the SOAP api changes, you need to update your interface definition as well.
The class is partial so you could make the class implement an interface in the partial class part you write.
You can then mock the interface.
I worked out a technique that will work for the case where the class is non-partial. Suppose this is the original class:
// Generated class, can't modify.
public class SomeClass
{
// Non-virtual function, can't mock.
public void SomeFunc() { //... }
}
First, extract the interface from that class:
public interface ISomeClass
{
void SomeFunc();
}
Now make a new class that inherits from both of the above:
public SomeClass2 : SomeClass, ISomeClass
{
// The body of this class is empty.
}
Now you can use SomeClass2 in your program. It will behave the same as SomeClass. And you can mock ISomeClass.

Categories

Resources