SettingsProvider class - should it be in DAL or BLL project? - c#

I have in my application layers: Web, DAL and BLL.
Where should I place SettingsProvider class (to get values from web.config)? I think it should be inside DAL project. Am I right?
public class SettingsProvider : ISettingsProvider
{
public string UploadImagesPath
{
get { return ConfigurationManager.AppSettings["UploadImagesPath"]; }
}
..............
}

I don't agree that there is a right layer for you to put that class since you reading values from the config file based on keys provided and it can be needed by one or all of the layers. In the case of all layers using this class, you can as well setup a common Class Library project and reference it in layers where it is needed.

Since settings are specific to Web application (because they are defined in Web.config) I think you should put it in Web application and somehow "send" them to BLL or DAL, wherever appropriate. And since you already have an ISettingsProvider interface defined, you could make a use of some IoC container and registering this interface on Web's bootstrap method (or sth like that). Or just send your ISettingsProvider (maybe static variable) arround into DAL and BLL from Web application.

Related

Where to put client DLLs in n-tier architecture for calling external API

We have an n-tier architecture with a DAL -> BL -> UI, seperation. In our DAL we have EF for our database access.
We have a requirement to make calls to an external API from a different company. We have been given a couple of client .DLL files with libraries to make the process seamless.
We are struggling to decide where the .DLL files should reside. Should we put them in the DAL and then do the calls in the DAL because it is data access or should we put it all in the BL and make the external calls in there. Therefore not touching the DAL and keeping it isolated and solely for database access.
Would greatly appreciate any advise on this.
Ok, it sounds like you should reference the external assembly on your data access layer beucase the main object of this assembly is to retrieve data. But, when you consume the data access layer on the business layer you also have this principal. I would go by Business Layer. Given it is part of your logic, then you should put this kind of access there.
Another point: If you are not comfortable to reference this assembly on you class library business layer project, you could abstract it into an interface and inject it (by IoC for sample) on your business layer. Using some approach like this, you will keep it on the business layer and isolated the access of this API.
For sample, add it on your Domain Model layer (if you are using one):
public interface IExternalDataService
{
IEnumerable<SomeDto> Getdata();
SomeDto Getdata(object id);
}
On an another class library project you add the refence of the assembly and make the API call, implementing this interface:
public class ExternalDataService : IExternalDataService
{
public IEnumerable<SomeDto> Getdata()
{
// consume the API (dll) here...
}
public SomeDto Getdata(object id)
{
// consume the API (dll) here...
}
}
On your BL classes, depend of the interface:
public class CustomerService
{
public CustomerService(IExternalDataService externDataService)
{
...
}
}
First of all we need to be clear of what exactly is the external DLL providing us, in most of the cases the external dll wraps up the business logic of that particular third party application.
Which, that's why in my opinion, should be kept along in the BL of your application. And hence agreeing with your last statement, to put DAL isolated just taking care of database operations.

What's the recommended folder structure of catalogs in project using IoC

I've read few articles and watched many lectures/tutorials on YT about DI and IoC, but I didn't find any recommended layout of catalogs in VS solution.
I'm talking about the project (a game for example) where you have few classes/interfaces, logger, database provider, wcf services, wpf presentation layer (that's actually different project)...
Is there any pattern project, that shows how should I organize my project, so next, experienced programmer will not waste time figuring out what's going on? Like we're talking about "self commented code", I'm talking about "self commented project structure".
For example, should I put all interfaces into "Interfaces" catalog? Or should I (in case of logger) create "Logger" catalog and put there interface, classes, class with extension methods (all, focused on logging). Code focused on Board, in "Board" catalog. Separate catalog for "Field" etc etc..
Right now the structure looks like that. I'm not sure about "Business" there and Logger. I have interface in different catalog then other logger classes. Should I call Log4Net provider? or adapter? or decorator? It's just a logger class implementing ILogger interface. Here is the screen: link
Here is the sample code (there is no IoC yet, but everybody will notice there will be 3 interfaces there mapped. Very simple):
public class Game
{
public IBoard Board { get; set; }
public Game(IBoard board)
{
Board = board;
}
}
public interface IBoard {}
public class Board : IBoard
{
public IField[,] Fields { get; set; }
public Board(IField field, int boardWidth, int boardHeight)
{
Fields = new IField[boardHeight, boardWidth];
Fields.Initialize();
}
}
public interface IField {}
public class Field : IField {}
public interface ILogger
{
void Log(LogEntry entry);
}
What I usually do is that I have a MyApplication.Core (Class library) layer, which contains all the applications interfaces with as little (read: none) third-party dependencies, e.g. ILogger, ICommand or IQuery<TResult>.
Next I have a MyApplication.Domain (Class library) layer which contains all the application domain specific knowledge - this is the business layer. This is implementations of the core interfaces ICommand, IQuery<TResult>. These implementations then have an dependency on e.g. ILogger. Never concrete implementations.
Then I have the MyApplication.Infrastructure (Class library) which is where all the service interfaces from MyApplication.Core is implemented, e.g. ILogger. Here you can have dependencies on third-party libraries such as Log4Net.
Then last I have the presentation layer, which is in my case usually an MVC applications so I would name this MyApplication.Web.Mvc. All controllers have only dependencies on the interfaces. Never concrete implementations. This layer is also responsible of bootstrapping all the interfaces to the concrete implementations using a Composition Root.
TL;DR:
MyApplication.Core (Application Interface Layer)
MyApplication.Domain (Business Logic)
MyApplication.Infrastructure (Implementations of Application Interface Layer)
MyApplication.Web.Mvc (Presentation and Composition Root Layer)
From Microsoft's "Common web application architectures".
The Application Core Project
The Application Core holds the business model, which includes entities, services, and interfaces. These interfaces include abstractions for operations that will be performed using Infrastructure, such as data access, file system access, network calls, etc. Sometimes services or interfaces defined at this layer will need to work with non-entity types that have no dependencies on UI or Infrastructure. These can be defined as simple Data Transfer Objects (DTOs).
The Infrastructure Project
The Infrastructure project typically includes data access implementations. In a typical ASP.NET Core web application, these implementations include the Entity Framework (EF) DbContext, any EF Core Migration objects that have been defined, and data access implementation classes. The most common way to abstract data access implementation code is through the use of the Repository design pattern.
In addition to data access implementations, the Infrastructure project should contain implementations of services that must interact with infrastructure concerns. These services should implement interfaces defined in the Application Core, and so Infrastructure should have a reference to the Application Core project.
The ASP.NET Core Web App Project
The user interface layer in an ASP.NET Core MVC application is the entry point for the application. This project should reference the Application Core project, and its types should interact with infrastructure strictly through interfaces defined in Application Core. No direct instantiation of or static calls to the Infrastructure layer types should be allowed in the UI layer.
A starting point repo for Clean Architecture with ASP.NET Core
https://github.com/ardalis/CleanArchitecture

Enterprise Library Logging Block Get Configuration From web.config

I've a Web API application. In the solution of the application, there are several projects.
And all the API's are in one single project. And there is one project for business layer.
We want to write one logging class containing all the relevant methods in the business layer project and we are going to use "Enterprise Library Logging Block".
What is the correct procedure to get the related configuration from the web.config in the class of the business layer project.
Thanks in advance.
If the configuration is contained in web.config and the business layer assembly executes in the same appdomain as the Web API application then the only thing you will need to do is bootstrap the blocks you are using (in this case it sounds like just logging).
You could do this at application startup (e.g. App_Start):
Logger.SetLogWriter(new LogWriterFactory().Create());
In this approach the Business Layer will use the static facade Logger.Write to write LogEntries.
A better approach would be to create a small wrapper around a LogWriter that will bootstrap the block and expose the LogWriter for use in the business layer (and anywhere that needs logging). This is a bit more friendly for dependency injection since it's easy to register in a container and can be passed in as a dependency.
public class Logger
{
private Lazy<LogWriter> logWriter = new Lazy<LogWriter>(() =>
{
LogWriterFactory factory = new LogWriterFactory();
return factory.Create();
});
public LogWriter LogWriter
{
get { return logWriter.Value; }
}
}
Since internally LogWriter is a singleton and you only want to bootstrap once you would probably make the custom Logger class a singleton. (If you don't care about having an instance you could make Logger entirely static.)

How to handle layer specific Dependency Injection in a reusable dll with ninject?

We use ninject as our DI solution. How do I create a self sustaining class library dll with its own internal IOC. Basically I have created a service that does something and I want to register the bindings in the dll and just hand it to other people. I don't want them to care about any binding in my dll.
In the dll:
public class FirstService : IFirstService
{
public FirstService(ISecondService secondService, IThirdService thirdService)
{
//Saves locally
}
//Does stuff with second and third services
}
What the end user does:
public class ThirdService : IThirdService
{
//Create the actual implementation of this
}
What I want inside the dll:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IFirstService>.To<FirstService>();
kernel.Bind<ISecondService>.To<SecondService>();
}
I don't think I want to use IKernel here though, due to possible memory leakage.
There are 4 basic design approaches to DLLs that are commonly in use:
An application layer.
A plug-in.
A library.
A framework.
It sounds like you have one of the last 2, but it is not possible to tell based on your question which prototype you are referring to.
For an application layer, you would typically compose the components inside of the application, in the composition root, as close to the point of entry of the main executable application as possible.
For a plugin, it would typically have its own internal composition root that is fired by some method or event of the application it is plugging into (based on that application's composition root). This is sometimes facilitated by modules in DI containers.
A library would typically not have any internal composition, but would provide an API (sometimes implemented as a fluent builder) that makes it easy for the client application to compose the pieces together. See this post for a couple of ideas about how to do that.
A framework would need to have 1 or more explicit extension points for the application to integrate into. Think of how MVC controllers work. There is an internal scanning implementation that by default can instantiate any object that implements a certain interface. There is also an abstract factory that can be used to inject dependencies if the default constructor is not available (in MVC, that is IControllerFactory). See this post for more information about how to make a DI friendly framework.

External config file to be used by multiple DLLs

I have multiple DLLs that are used to read/write data into my database.
There is a presentation layer DLL and a data access layer DLL. I want these DLLs to share a set of the connection strings.
My idea is to store the connection string in a seperate DLL in the external configuration file. I'm not sure whether it's a good idea and whether I can reference that external DLL in both presentation and data access layers.
The other question is whether I should write a helper class to read the data from the external config file or whether I should be using built in .Net methods?
Thank you
Isolate the configuration file access code in a separate class. Make the configuration data (connectionstrings and whatnot) available via an interface on that class. Let the interface live in a shared assembly. Let any class that needs this interface get a reference to an instance of the configuration class via dependency injection. If you're not already using a DI framework I can highly recommend Autofac.
What have you achieved? Presentation and data access classes are now only dependent on a shared interface definition. They don't care what the implementation of that interface is, whether it reads connection strings from web.config, machine.config or some other store. Even better, you can now more easily test your classes by faking the implementation.
Update: First, to illustrate making the configuration data available via an interface. Say we have the following conffiguration service:
public interface IConfigurationService
{
string ConnectionString {get;}
}
public class ConfigurationService : IConfigurationService
{
string ConnectionString {get;}
public ConfigurationService()
{
// load configuration
}
}
My data access class could use this class directly:
public class DataAccess
{
private string _connectionString;
public DataAccess()
{
var config = new ConfigurationService();
_connectionString = config.ConnectionString;
}
}
The problem with this approach is coupling. DataAccess is now directly dependent on the ConfigurationService class. Any tests we write for DataAccess will inadvertently be affected by the ConfigurationService class. Also, should we need to switch out the implementation of ConfigurationService it would require changes to DataAccess (and all other classes directly dependent on this class).
To solve this, we invert the dependency hierarchy and references an interface instead of the concrete class, like this:
public class DataAccess
{
private string _connectionString;
public DataAccess(IConfigurationService configurationService)
{
_connectionString = configurationService.ConnectionString;
}
}
The data access class is now oblivious as to what the configuration service implementation is and how that instance is created.
As far as I'm aware, DLL files cannot make use of .net config items like app.config files, so if you want your dll to be configurable through say an xml file, you'll have to write it yourself.
I can store the connection string in the machine.config, but once again not sure about all the implications....

Categories