Since ABusiness
is a service that does something it would normally be setup like:
public interface IABusiness
{
void functionInABusiness();
}
public class ABusiness : IABusiness
{
// making the variable private readonly ensures that nothing
// can set it after the constructor does (thus it can never be null)
private readonly IADataAccess aDataAccess;
public ABusiness(IADataAccess aDataAccessParam)
{
// Guard clause ensures you cannot set this.aDataAccess to null
if (aDataAccessParam == null)
throw new ArgumentNullException(nameof(aDataAccessParam));
this.aDataAccess=aDataAccessParam;
}
public void functionInABusiness()
{
// Do something with aDataAccess
}
}
Then you would add IABusiness
as a dependency of BBusiness
.
public interface IBBusiness
{
void function();
}
public class BBusiness : IBBusiness
{
private readonly IBDataAccess bDataAccess;
private readonly IABusiness aBusiness;
public BBusiness(IBDataAccess bDataAccessParam, IABusiness aBusinessParam)
{
if (bDataAccessParam == null)
throw new ArgumentNullException(nameof(bDataAccessParam));
if (aBusinessParam == null)
throw new ArgumentNullException(nameof(aBusinessParam));
this.bDataAccess=bDataAccessParam;
this.aBusiness=aBusinessParam;
}
public function()
{
this.aBusiness.functionInABusiness();
// Do something else...
}
}
In your composition root, you would then setup Unity to associate IABusiness
with ABusiness
and IBBusiness
with BBusiness
. Do note that some projects use conventions that do this step automatically if the classes and interfaces are named a certain way or put in a certain place, etc.
container.RegisterType<IABusiness, ABusiness>();
container.RegisterType<IBBusiness, BBusiness>();
container.RegisterType<IADataAccess, ADataAccess>();
container.RegisterType<IBDataAccess, BDataAccess>();
The whole idea is that you do not reference the ABusiness
class directly from the BBusiness
class, so you can inject a different instance of IABusiness
into BBusiness
(for testing, or to create a decorator class around IABusiness
that adds additional responsibility to it, etc.)
Also, the IABusiness
interface might be in a different assembly than ABusiness
(for example), so the BBusiness
assembly doesn't need to reference the ABusiness
assembly.
Do note you are not following Microsoft's capitalization conventions, which may make this code difficult to maintain for those following you. Method names should be Pascal case in .NET, like FunctionInABusiness()
.