Loosely coupling class - c#

I'm making an application that uses an external API. But I don't want my application to be dependant on the API. So I have been reading about how to achieve this. I read that the thing I want is loose coupling. I want to loosely couple my class that uses the external API from the rest of my application. My question is how do I achieve this. If read about different design patterns, I can't find one that helps with my problem.
public class GoogleCalendarService
{
private const string CalendarId = ".....";
private CalendarService Authenticate(string calendarId)
{
...
}
public void Create(Booking newBooking, string userId)
{
...
InsertEvent(newEvent, userId);
}
private void Insert(Event newEvent, string userId)
{
call authenticate account
....
}
public List<Booking> GetEvents()
{
call authenticate account
...
}
}
Above is my code for the class that uses the external API. In the rest of my application I use this class the following way:
public class MyApplication
{
private void MyFunction()
{
GoogleCalendarService googleCalendarService = new GoogleCalendarService();
googleCalendarService.CreateEvent(..., ...)
}
}
I do this on multiple places in my application. So my question is: How can I loosely couple the API class from the rest?
Edit: I probably want a general calendar service interface that makes it easier to replace the google calendar service with an other calendar service when needed.

that makes it easier to replace the google calendar service with an other calendar service
The main pattern you will want to look at is Adapter. But you would want to use that in combination with Dependency Injection.
The DI first:
public class MyApplication
{
// constructor injection
private IGeneralCalendarService _calendarService;
public MyApplication(IGeneralCalendarService calendarService)
{
_calendarService = calendarService;
}
private void MyFunction()
{
_calendarService.CreateEvent(..., ...)
}
}
And the Adapter would look something like
public class GoogleCalendarServiceAdapter : IGeneralCalendarService
{
// implement the interface by calliong the Google API.
}
In addition you will need generic classes for Event etc. They belong to the same layer as the interface.

You need to write a wrapper around that API. And rewrite every Output/Input of that API with your wrapper IO. And after that, you can take advantage of Dependancy Injection to use your own code. By this way you can have an abstraction layer around that API

Related

SOLID-principle attempt, solid or not solid?

In our layered architecture I am designing a BLL logic component called AppHandover and have written the basic high level code for this. I want it to follow the SOLID-principles and be loosly coupled, adopt separation of concern and be testable.
Here is what AppHandover should do
Check if User owns app. If not throw an error
remove history if possible (ie no more apps are assigned to user)
transfer the ownership to the next instance
Quesion is, am I on the right track and does the following sample seem SOLID?
public interface ITransferOwnership
{
void TransferOwnership(string userId, string appId, TransferDirection transferDirection);
}
public interface IOwnershipVerification
{
bool UserOwnsApp(string userId, int budgetId, string appId);
}
public interface IPreserveHistoryCheck
{
bool ShouldDeleteTemporaryBudgetData(string userId, int budgetId);
}
public interface IRemoveHistory
{
void DeleteTemporaryBudgetData(string userId, int budgetId);
}
Handover process implementation
public class AppHandoverProcess : KonstruktDbContext, ITransferOwnership
{
private IOwnershipVerification _ownerShipVerification;
private IPreserveHistoryCheck _preserveHistory;
private IRemoveHistory _removeHistory;
private ITransferOwnerShip _transferOwnership;
public AppHandoverProcess()
{
}
public AppHandoverProcess(IOwnershipVerification ownerShipVerification,
IPreserveHistoryCheck preserveHistory,
IRemoveHistory removeHistory)
{
_ownerShipVerification = ownerShipVerification;
_preserveHistory = preserveHistory;
_removeHistory = removeHistory;
}
public void PerformAppHandover(string userId, string appId, int budgetId)
{
if (_ownerShipVerification.UserOwnsApp(userId,budgetId,appId)) {
if (_preserveHistory.ShouldDeleteTemporaryBudgetData(userId, budgetId))
{
_removeHistory.DeleteTemporaryBudgetData(userId, budgetId);
}
//handover logic here..
_transferOwnership.TransferOwnership(userId, appId, TransferDirection.Forward);
}
else
{
throw new Exception("AppHandover: User does not own app, data cannot be handed over");
}
}
}
Concerning the code you outlined above I definitely think you're on the right track. I would push the design a little further and define TransferOwnership as an additional interface.
Following this approach your AppHandoverProcess is completely decoupled from it's client and the behaviour will be defined in the service configuration.
Enforcing an isolation for the TransferOwnership will allow you to easily UnitTest any object implementing the interface without the need to mock AppHandoverProcess dependency.
Also any AppHandoverProcess test should be trivial as the only thing you'll need to make sure is the your services are invoke or that the exception is thrown.
Hope this make sense,
Regards.
I would make KonstruktDbContext as an injectable dependency. AppHandoverprocess should not inherit from it as it looks like it is a different responsibility.

Azure Queue client Dependency injection

I have an azure application developed using MVC Web API, and it uses Ninject as the dependency injection framework, here there are number of queues used to communicate with the other worker roles responsible for the background processing.
To be able to unit test I decided to wrap the QueueClient with class called QueueClientWrapper and use an interface named IQueueClientWrapper
the class and interface looks like follows,
public interface IQueueClientWrapper
{
void Send<T>(T message);
}
public class QueueClientWrapper : IQueueClientWrapper
{
private QueueClient _queueClient;
public QueueClientWrapper(QueueClient queueClient)
{
_queueClient = queueClient;
}
public void Send<T>(T message)
{
_queueClient.Send(new BrokeredMessage(message));
}
}
However the limitation of this approach is I need to pass the QueueClient into the constructor, which is not possible with the Ninject.
So I was thinking changing the interface like,
public interface IQueueClientWrapper
{
void Send<T>(string connectionString,string queueName,T message);
}
so that I can use Ninject to inject the QueueClientWrapper without needing to pass constructor argument,
The issue I have now is, usually it's not recommended to create multiple queue client objects and we have to re-use same instance. So what's the best way to address this (I thought of using a static Hashtable and use to store queue name, queue client pairs, but I'm not very happy with that approach either)?
Dealing with Dependency Injection and Azure Queue
This question is from 2014, but here is a 2022 answer
You will need these 2 official azure extensions :
Azure.Storage.Queues (Contains the queue service)
Microsoft.Azure.Functions.Extensions (Contains helpers for the Startup.cs)
Add this line to your Startup.cs in the Configure method :
builder.Services.AddAzureClients(builder =>
{
builder.AddQueueServiceClient(configuration.GetValue<string>("AzureWebJobsStorage"));
});
And the constructor where you want the service :
public QueueHandlingService(QueueServiceClient queueClient)
{
_queueClient = queueClient;
//Or _queueClient = queueClient.GetQueueClient("myqueue-items");
}
Here are the docs for :
AddAzureClients
AddQueueServiceClient

Design pattern for API entry point?

I'm creating a class library API that wraps business logic and access to an SQL Server database via Entity Framework 6.
I've designed it using the Unit of work and repository patterns.
The purpose is to make it easy to use and to unit test.
Business logic and validation will be performed in the service layer.
I will not use an IOC container because I feel that it would complicate the API
usage.
The project have 15 repositories and services
The current design is as follows:
Service Layer A -> Unit of work -> Repository A and or B
Service Layer B -> Unit of work -> Repository B and or A...
...
public class ServiceA : IServiceA, IService
{
private readonly IUnitOfWork unitOfWork;
public AssetService(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
...
public IList<DomainObjectA> GetAll()
{
return unitOfWork.RepositoryA.GetAll();
}
public void Dispose()
{
unitOfWork.Dispose();
}
...
}
public class UnitOfWork : IUnitOfWork
{
private readonly MyDbContext context = new MyDbContext();
private IRepositoryA repositoryA;
private IRepositoryB repositoryB;
...
public IRepositoryA RepositoryA
{
get { return repositoryA = repositoryA ?? new RepositoryA(context); }
}
public IRepositoryB RepositoryB
{
get { return repositoryB = repositoryB ?? new RepositoryB(context); }
}
...
public void Save()
{
context.SaveChanges();
}
public void Dispose()
{
context.Dispose();
}
}
public class RepositoryA : Repository, IRepositoryA
{
public RepositoryA(MyDbContext context)
: base(context) {}
public IList<DomainObjectA> GetAll()
{
return context.tblA.ToList().Select(x => x.ToDomainObject()).ToList();
}
...
}
Since this is an API that should be used by other projects, I need a nice and "fairly" easy to use interface for the user that consumes the API.
Because of this the UnitOfWork is created in this "public interface" between the user and the service layer, see below.
I also think it's best that the using-statement lies within the API so that the db-context is disposed properly and immediately after each service call.
I started out using the Proxy pattern for this:
Example:
public class ProxyA : Proxy, IServiceA
{
public IList<DomainObjectA> GetAll()
{
using (var service = GetService<ServiceA>())
return service.GetAll();
}
...
}
public abstract class Proxy
{
protected T GetService<T>() where T : IService
{
return (T)Activator.CreateInstance(typeof(T), new object[] { new UnitOfWork()});
}
}
But this would require me to create a proxy for each service. I could of course skip the service interface in the proxy and create a common proxy which handles all the services.
I've also looked at the Facade pattern but can't decide which pattern to use for this particular scenario.
My questions:
Is this a good approach or are there any other design patterns that will solve this problem?
Also, should there be one public API entry point or several, grouped by some business logic?
I see nothing wrong with your design and the patterns you use.
Regarding the proxy pattern it is your call if you want to use it or not. As you mention you have to create boiler plate code to create one for every service. If it is arguable if you want to use it only to hide the call to the db service, or you prefer to add that line of code every time you call the service (and make sure you do it to avoid leaks). Also you may consider if you may need to add extra functionality in the Proxy in the future, which will put extra weight to create the proxy option.
Regarding a single entry point or several, I would create a ServiceA, ServiceB, ServiceC etc (so several) grouped for business logic domains. Typically you'll have between 5-20 (just an approximate number to give an idea of the magnitude)
You may want to review the interface segregation principle which supports this idea
http://en.wikipedia.org/wiki/Interface_segregation_principle

WCF and DI and Business logic layer, How to expose all methods of BLL, Best practice

I have
Public Class AuthorBLL : IAuthorBLL
{
Public Add_Author();
Public Get_AuthorsList();
}
Public Class BookBLL : IBookBLL
{
Public Add_Book();
Public Get_BookList();
}
Now I want to call my Business logic layer methods in my WCF layer and want to expose similar WCF OperationContracts methods to the UI.
My WCF class looks like this:
Public class WCFService : IWCFService
{
private IAuthorBLL _authorBLL;
private IBookBLL _BookBLL;
public WCFService(IAuthorBLL authorBll, IBookBLL bookBll)
{
_authorBLL = authorBll;
_bookBll = bookBll;
}
Public WCF_Add_Author (serializable_author author);
{
_authorBLL.Add_Author();
}
Public WCF_Get_AuthorsList()
{
_authorBLL.Get_AuthorList();
}
Public WCF_Add_Book (serializable_book book);
{
_bookBll.Add_Book();
}
Public WCF_Get_BookList()
{
_bookBll.Get_BookList();
}
}
Question:
My question is regarding the WCF constructor where i have to pass all these Business logic layer objects as constructor parameters to achieve DI. How can i make it generic so that if in the future I have publisherBLL, VentorBLL, CustomerBLL and so on... i don’t have to pass them all in the WCF constructor?
I know it’s the way dependency injection works but what if i have 50 BLL objects; will i have to pass them all in the WCF constructor. Is there any way to avoid it? Any design pattern or technique which can give me better solution to this.
I need to keep one WCF service which can expose all method whether its Authors, books, publishers, clients, customers or retailers. One service should expose all CRUD methods.
EDit:
As you are saying use Ninjet or CastleWinsor for IOC where you can create the containers to define DI. but still you have to define the constructor based parameters in the WCF constructor in WCF class.
Do we will have to define the constructor parameters as below. or if the WCF is too big to expose so many methods then what is a solution for an application where you have to do CRUD for Authors, books, employees (working in a shop), publishers, HR and payroll modules. every module have webpages and calling WCF service to do CRUD. as we never know when we will need to move on to Mobile interface or how many other applications will use the same methods so we want to expose all through WCF service. What should i do?
private IAuthorBLL _authorBLL;
private IBookBLL _BookBLL;
private IClientBll _ClientBll;
private IPublisherBll _PublisherBll;
private IHRBll _HRBll;
private IEmployeeBll _employeeBll;
public WCFService(IAuthorBLL authorBll, IBookBLL bookBll, IClientBll
clientBll, IPublisherBll publisherBll, IEmployeeBll
employeeBll, IHRBll HRBll)
{
_authorBLL = authorBll;
_bookBll = bookBll;
_authorBLL = authorBll;
_ClientBll = clientBll;
_PublisherBLL = publisherBll;
_HRBll = HrBll;
_EmployeeBLL = EmployeeBll;
}
As i have so many front end pages to deal with employees, authors, clients, books, publishers. What should i do.
You've pretty much answered yourself. If you use some DI framework like Unity or Ninject then you won't have to bother about passing 50 arguments to your constructor - just retrieve the service object from the DI framework's factory and it will care about providing appropriate arguments. Maybe what are you missing is that you can register your service in the DI framework along with it's dependencies.
Simple example with Unity:
In some kind of a Bootstrapper class which initializes whole application:
public void Run()
{
//...
SetupContainer();
//...
RunWebService();
//...
}
public void SetupContainer()
{
//This can also be done using a configuration file
this.container.RegisterType<IAuthorBLL, AuthorBLLImpl>();
this.container.RegisterType<IBookBLL, BookBLLImpl>();
this.container.RegisterType<IOther1BLL, Other1BLLImpl>();
//...
this.container.RegisterType<IOther50BLL, Other50BLLImpl>();
}
public void RunWebService()
{
this.container.RegisterType<IWCFService, WCFService>(
new ContainerControlledLifetimeManager());
var serviceSingleton = this.container.Resolve<IWCFService>();
//... proceed with service setup and run
}
Note that usually SetupContainer is split between different modules. Each of them registers its own classes.

How to write functionality using DDD / CQRS

I have a bank account domain as listed below. There can be SavingsAccount, LoanAccount, FixedAccount and so on. One user can have multiple accounts. I need to add a new functionality – get all accounts for a user. Where should be the function written and how?
It would be great if the solution follows SOLID principles( Open-Closed principle,…) and DDD.
Any refactoring that would make the code better is welcome.
Note: The AccountManipulator will be used by a website client over a web service.
namespace BankAccountBL
{
public class AccountManipulator
{
//Whether it should beprivate or public?
private IAccount acc;
public AccountManipulator(int accountNumber)
{
acc = AccountFactory.GetAccount(accountNumber);
}
public void FreezeAccount()
{
acc.Freeze();
}
}
public interface IAccount
{
void Freeze();
}
public class AccountFactory
{
public static IAccount GetAccount(int accountNumber)
{
return new SavingsAccount(accountNumber);
}
}
public class SavingsAccount : IAccount
{
public SavingsAccount(int accountNumber)
{
}
public void Freeze()
{
}
}
}
READING:
When to use the CQRS design pattern?
In domain-driven design, would it be a violation of DDD to put calls to other objects' repostiories in a domain object?
Refactoring domain logic that accesses repositories in a legacy system
Which of these examples represent correct use of DDD?
Good Domain Driven Design samples
Advantage of creating a generic repository vs. specific repository for each object?
if your AccountManipulator is a Façade to your domain, I wouldn't put the account number in the constructor. I would refactor it this way:
public class AccountManipulator
{
private AccountFactory _factory;
private UserRepository _users;
public AccountManipulator(AccountFactory factory, UserRepository users)
{
_factory = factory;
_users = users;
}
public void FreezeAccount(int accountNumber)
{
var acc = _factory.GetAccount(accountNumber);
acc.Freeze();
}
public IEnumerable<IAccount> GetAccountsOf(User user) {
return _users.GetAccountIds(user).Select(_factory.GetAccount);
}
}
public interface UserRepository {
IEnumerable<int> GetAccountIds(User user);
}
In order to state if your domain is SOLID, you should analyze it with the principle:
Single Responsibility: every object has is own responsibility (and only that one):
AccountFactory: creates IAccounts
SavingsAccount: implementation of IAccount that reads from/writes to (a database? a web service?)
AccountManipulator: provide a minimal and simple set of operations to do with domain objects.
Open/Closed: are you classes are open to extensions and closed to changes?
AccountFactory: well, no. If you write a new implementation of IAccount, in order to use it you have to change AccountFactory. Solution: abstract factory
SavingsAccount? It depends if it will use external dependencies. Need more code to say.
AccountManipulator: yes. If you need to do another operation with your domain objects, you can use directly the other services without change AccountManipulator. Or you can inherit from it
Liskov substitution: can you substitute any class with another implementation? Need more code to say. You have no other implementations of IAccount or IAccountFactory now
Dependency Inversion:
AccountManipulator should depend on abstractions: AccountFactory and UserRepository should be interfaces.
Firstly, to really answer your question it's important to know why you need to get all user accounts? Are you:
Fetching a list of accounts to display on screen for the user to
then perform a command/transaction against a single account?
Performing a single command/transaction on all of the users accounts - such as 'Freeze All User Accounts'?
The reason I ask is because you only need to consider the DDD aspect if it's the latter. If the reason for this 'functionality' is the former (and after reading your question I suspect it is) - I really recommend just creating a thin query service layer that gets the user's account data you need for the screen. You don't need to add the 'restrictions' of DDD for this; there are no transactions or model state changes involved. Providing this functionality doesn't have to involve the domain model at all. Just define some simple POCO DTO's and use Entity Framework to get the data and pass it back to the UI.
This is what CQRS is about; you don't need repositories, factories or aggregates to give the UI a list of accounts for the user to choose from - you would be over complicating it and making A LOT more work for yourself.
If there is a scenario that requires a single transaction over all of the user's accounts then I'd do something like:
public class AccountService : IAccountService
{
private IAccountRepository _accountRespository;
public void FreezeAllAccountsForUser(Guid userId)
{
IEnumerable<IAccount> accounts = _accountRespository.GetAccountsByUserId(userId);
using (IUnitOfWork unitOfWork = UnitOfWorkFactory.Create())
{
foreach (IAccount account in _accounts)
{
account.Freeze();
_accountRespository.Save(account);
}
}
}
}
Where AccountService is a webservice, i.e. the Application Layer.
In summary, my advice is: Only consider DDD in the context of commands that require transactions. For fetching lists of data; create a simple query service that the UI can consume.
P.S. I've noticed the misuse of the Factory pattern in your question and some of the answers. Factories are designed to provide an object's CREATION strategy, given particular data. There shouldn't be a 'GetAccount(accountId)' method that calls the database; repositories call the database then pass data to a factory to create the object.
First of all why do you need AccountManipulator? It does absolutely nothing, but makes the code more complicated.
As for getting all accounts of a User, the most logical place to put this method would be in the User class. You could pass an account factory to that method, further implementation would probably depend on how you store accounts.
I'd rename 'AccountFactory' to AccountRepository and put an extra method in it GetAccountsForUser( int userId ) which retrieves all Accounts for a specific user.
If AccountManipulator is a webservice, then this class will use the AccountRepository, like this:
public class AccountManipulator
{
public void FreezeAccount( int accountNr )
{
var repository = new AccountRepository();
var account = repository.GetAccount(accountNr);
account.Freeze();
repository.Save(account);
}
public ICollection<Account> GetAccountsForUser( int userId )
{
var repository = new AccountRepository();
return repository.GetAccountsForUser (userId);
}
}

Categories

Resources