How to have a generic method in a data access layer interface? - c#

I want to have a generic method, that converts a few known types, to their equivalent types that is accepted by the database to insert them.
public class MongoDataAccess : IDataAccess
{
public Task InsertAsync<T>(string collectionName, T item)
{
// convert T which should be `Student`, `University` etc
// to `StudentDocument`, 'UniversityDocument` etc
}
}
How can I do this, probably using interfaces to apply restrictions?

In addition to having a "data access facade" IDataAccess, you can implement "entity handler" IDataAccess<T> per each entity type (Student, University, etc). Application code will "talk" to the DAL facade, and the DAL facade will delegate to a concrete entity handler.
The DAL facade can look like this:
public interface IDataAccess<TEntity>
{
// no need for collectionName parameter
// because each concrete entity handler knows its collection name
Task InsertAsync(TEntity entity);
// .... other CRUD methods
}
An implementation of a concrete entity handler can look like this:
public class StudentDataAccess : IDataAccess<Student>
{
// initialized elsewhere in this class
private MongoCollection<StudentDocument> _collection;
public Task InsertAsync(Student entity)
{
var document = ConvertToDocument(entity);
return _collection.InsertOneAsync(document);
}
private StudentDocument ConvertToDocument(Student entity)
{
// perform the conversion here....
}
}
This is how the DAL facade will delegate calls to a concrete entity handler:
public class DataAccess
{
public async Task InsertAsync<T>(T entity)
{
//... obtain an instance of IDataAccess<T>
var enityHandler = GetEntityHandler<T>();
return entityHandler.InsertAsync(entity);
}
private IDataAccess<T> GetEntityHandler<T>()
{
// you can use a DI container library like Autofac
// or just implement your own simpliest service locator like this:
return (IDataAccess<T>)_handlerByEntityType[typeof(T)];
}
// the following simplest service locator can be replaced with a
// full-blown DI container like Autofac
private readonly IReadOnlyDictionary<Type, object> _handlerByEntityType =
new Dictionary<Type, object> {
{ typeof(Student), new StudentDataAccess() },
{ typeof(University), new UniversityDataAccess() },
// ... the rest of your entities
};
}

Use this interface.
IConvertible<TSource, TResult>
{
Task<TResult> Convert(string collectionName);
}
Your datatypes like Student and University must implement from this.

Related

Create instance by enum value + dependency injection

I have some handler classes in my application which are created in runtime according to passed enum value. It looks like this:
public interface IMyHandler
{
void Handle();
}
public class SimpleHandler : IMyHandler
{
public void Handle()
{
//logic here...
}
}
public class ComplexHandler : IMyHandler
{
public void Handle()
{
//logic here...
}
}
public enum HandlerTypes
{
Simple,
Complex
}
public class Hanlderfactory
{
public IMyHandler CreateHandler(HandlerTypes type)
{
switch(type)
{
case HandlerTypes.Simple:
return new SimpleHandler();
case HandlerTypes.Complex:
return new ComplexHandler();
default:
throw new NotSupportedException();
}
}
}
It's ok for me. But there is a problem here if I want to inject some components in my handlers like this:
public class SimpleHandler : IMyHandler
{
public SimpleHandler(IComponentOne c1, IComponentTwo c2, IComponentThree c3)
{
//...
}
public void Handle()
{
//logic here...
}
}
I use Unity IoC container and of course I want to use it here. But it looks ugly to call Resolve method here manually. Am I on wrong path? How to use both of this patterns together gracefully? Is it a single option here to call IoC container inside facotry?
UPDATE: I tried to use injection of delegate with InjectionFactory class. It works fine. But in this case if I need such factory logic in two applications I need to register this delegate and mapping between enums and classes in both applications startup:
var container = new UnityContainer();
container.RegisterType<IMyHandler, SimpleHandler>(HandlerTypes.Simple.ToString());
container.RegisterType<IMyHandler, ComplexHandler>(HandlerTypes.Complex.ToString());
container.RegisterType<Func<HandlerTypes, IMyHandler>>(new InjectionFactory(c => new Func<HandlerTypes, IMyHandler>(type => c.Resolve<IMyHandler>(type.ToString()))));
Using Enum with a factory is a code smell that indicates you need to do more refactoring.
An alternative is to use the strategy pattern as in this example. Note the use of Type instead of an Enum ensures you only have to change one piece of code when the design changes (you could alternatively use a string datatype).
Another alternative would be to inject a Func into the factory so your DI container can resolve instances.
Injecting the container into an abstract factory is a way of making a framework extension point. As long as the factory is part of your composition root, this is okay.

generic method in a non-generic class

I'm trying to create a simple data access class which acts as a library to return various entities. All my entity classes are generated via the Linq-to-SQL mapper in VS 2013, and all of them can be returned from the dataContext via Find(primary id)
I'd like to just define generic Find, Delete, Update etc without having to repeat it for every table/object but I don't want to create a Repository pattern.
How do I create a generic method that works regardless? This is what I have and of course it says T not defined, but I thought we could create generic methods in non-generic classes, so what am I doing wrong?
What I'd like to do is something like
var c = DAL<Customer>.Find(id)
var e = DAL<Employee>.Find(id)
... etc.
The code I attempted to write is
public class DAL
{
private string _key;
private DataContext _context = null;
//private DbSet<T> _table = null;
public DAL(string key)
{
_key = key;
_context = new DataContext();
}
public void Dispose()
{
_context.Dispose();
}
public DbSet<T> Find<T>(int id)
{
var d = _context.Set<T>();
//return d.Find(id);
}
}
I'm kind of lost... I do not want to define
public class DAL<T> where T:class
which ties each DAL to a type
This is the first time I'm venturing into generic nethods so any help appreciated
You can specify a generic method of a class, but you will need to use a constraint:
public class DAL
{
// .... previously written code
public DbSet<T> Find<T>(int id) where T : class
{
return _context.Set<T>();
}
}
You will also have to call it like this:
var dal = new DAL();
var data = dal.Find<Customer>(1);
Also note, that your code has a number of problems, you define a dispose method, but you don't implement the IDisposable interface, you're not actually returning anything from the method, etc..
Note: for all intents and purposes, this is still a repository pattern.
Something like this should work:
public T Find<T>(int id) where T : class
{
return context.Set<T>().Find(id);
}

Factory Interface Create Method with object Argument

I have a question about creating a factory interface with a create method that can cater for accepting different argument types depending on the implementation.
To give you a bit more background, I am using dependency in injection in a project, and require stateful objects to be generated at runtime - therefore I am injecting factories (rather than the objects themselves) to create these stateful objects. The problem I have come across is that, for some interfaces, the concrete implementations simply cannot have the same constructor argument types, and so the factories that create an instance of these interfaces require almost 'dynamic' arguments to be passed to the create method.
I have been going over this for a couple of days, and the following is the best solution I could come up with (namely, passing an object to the factory create method and casting it in the concrete implementation of the factory). I am really looking for feedback from people who have come across this scenario before, to hear what they came up with, and whether or not the solution I am proposing below is acceptable.
Apologies if this is missing any information, and many thanks in advance!
//
// Types...
//
interface IDataStore
{
List<string> GetItems();
}
public class XmlDataStore : IDataStore
{
public XmlDataStore(XmlDocument xmlDoc)
{
// Initialise from XML Document...
}
public List<string> GetItems()
{
// Get Items from XML Doc...
}
}
public class SQLDataStore : IDataStore
{
public SQLDataStore(SqlConnection conn)
{
// Initialise from SqlConnection...
}
public List<string> GetItems()
{
// Get Items from Database Doc...
}
}
//
// Factories...
//
interface IDataStoreFactory
{
IDataStore Create(object obj);
}
class XmlDataStoreFactory : IDataStore
{
IDataStore Create(object obj)
{
// Cast to XmlDocument
return new XmlDataStore((XmlDocument)obj);
}
}
class SQLDataStoreFactory : IDataStore
{
IDataStore Create(object obj)
{
// Cast to SqlConnection
return new SQLDataStore((SqlConnection)obj);
}
}
Based on this comment you need one factory which produces several types of IDataStore. You could accomplish by creating a open generic factory method in the singleton factory instance.
interface IDataStore<TStoreType>
{
void SetBaseType(TStoreType obj);
List<string> GetItems();
}
interface IDataStoreFactory
{
IDataStore<TStoreType> Create<TStoreType>(TStoreType obj)
}
class DataStoreFactory : IDataStoreFactory
{
public IDataStore<TStoreType> Create<TStoreType>(TStoreType obj)
{
if (obj.GetType() == typeof(SqlConnection))
{
var store = new SQLDataStore((SqlConnection)(Object)obj);
return (IDataStore<TStoreType>)store;
}
if (obj.GetType() == typeof(XmlDocument))
{ //... and so on }
}
}
class SQLDataStore : IDataStore<SqlConnection>
{
private readonly SqlConnection connection;
public SQLDataStore(SqlConnection connection)
{
this.connection = connection;
}
public List<string> GetItems() { return new List<string>(); }
}
You can use this factory like this:
var factory = new DataStoreFactory();
var sqlDatastore = factory.Create(new SqlConnection());
var xmlDatastore = factory.Create(new XmlDocument());
Your datastore factory would become a lot less complex if you would use a DI container. You could inject the container in the factory and retrieve your instances directly from the container, which would typically build your instances from bottom to top, including there own dependencies, lifetime management and so on. But be very carefull with this approach, it is the first step to using the service locator pattern which is an anti pattern
Not really sure if I understand your question correctly but to me it sounds a little odd to have factory instances which you use for the creation of your statefull objects as you call them.
To directly answer your question: generics are your solution. You rinterface becomes an open generic abstraction:
interface IDataStore<TStoreType>
{
List<string> GetItems();
}
interface IDataStoreFactory<TStoreType>
{
IDataStore<TStoreType> Create(TStoreType obj);
}
and your factory classes will look like this:
class XmlDataStoreFactory : IDataStoreFactory<XmlDocument>
{
IDataStore<XmlDocument> Create(XmlDocument document)
{
return new XmlDataStore(document);
}
}
class SQLDataStoreFactory : IDataStoreFactory<SqlConnection>
{
IDataStore<SqlConnection> Create(SqlConnection connection)
{
return new SQLDataStore(connection);
}
}
This will work, but from the examples you give I got the impression you're using factories throughout your codebase. Maybe I'm wrong on this point, but look at your design and minimize the number of factories. Needing a factory means mixing data with behaviour and this will always, eventually, get you into trouble.
For example, let's say you have some kind of service which adds the current user to a audit log when he logs in. This service offcourse needs the current user which is a typical example of runtime data (or contextual data). But instead of:
public class AuditLogService
{
public void AddApplicationSignIn(User user)
{
//... add user to some log
}
}
I know this is not a good example because you actually wouldn't need a factory for this class, but with the next code example you'll get the point:
public class AuditLogService
{
private readonly IUserContext userContext;
public AuditLogService(IUserContext userContext)
{
this.userContext = userContext;
}
public void AddApplicationSignIn()
{
var user = this.userContext.GetCurrentUser();
//... add user to some log
}
}
So by splitting data from behaviour you rule out the need for factories. And admitted there are cases where a factory is the best solution. I do think an IDataStore is not something you need a factory for.
For a good blog on splitting data and behaviour read here

Using the Generic repository/Unit of work pattern in large projects

I'm working on a quite large application. The domain has about 20-30 types, implemented as ORM classes (for example EF Code First or XPO, doesn't matter for the question). I've read several articles and suggestions about a generic implementation of the repository pattern and combining it with the unit of work pattern, resulting a code something like this:
public interface IRepository<T> {
IQueryable<T> AsQueryable();
IEnumerable<T> GetAll(Expression<Func<T, bool>> filter);
T GetByID(int id);
T Create();
void Save(T);
void Delete(T);
}
public interface IMyUnitOfWork : IDisposable {
void CommitChanges();
void DropChanges();
IRepository<Product> Products { get; }
IRepository<Customer> Customers { get; }
}
Is this pattern suitable for really large applications? Every example has about 2, maximum 3 repositories in the unit of work. As far as I understood the pattern, at the end of the day the number of repository references (lazy initialized in the implementation) equal (or nearly equal) to the number of domain entity classes, so that one can use the unit of work for complex business logic implementation. So for example let's extend the above code like this:
public interface IMyUnitOfWork : IDisposable {
...
IRepository<Customer> Customers { get; }
IRepository<Product> Products { get; }
IRepository<Orders> Orders { get; }
IRepository<ProductCategory> ProductCategories { get; }
IRepository<Tag> Tags { get; }
IRepository<CustomerStatistics> CustomerStatistics { get; }
IRepository<User> Users { get; }
IRepository<UserGroup> UserGroups { get; }
IRepository<Event> Events { get; }
...
}
How many repositories cab be referenced until one thinks about code smell? Or is it totally normal for this pattern? I could probably separate this interface into 2 or 3 different interfaces all implementing IUnitOfWork, but then the usage would be less comfortable.
UPDATE
I've checked a basically nice solution here recommended by #qujck. My problem with the dynamic repository registration and "dictionary based" approach is that I would like to enjoy the direct references to my repositories, because some of the repositories will have special behaviour. So when I write my business code I would like to be able to use it like this for example:
using (var uow = new MyUnitOfWork()) {
var allowedUsers = uow.Users.GetUsersInRolw("myRole");
// ... or
var clothes = uow.Products.GetInCategories("scarf", "hat", "trousers");
}
So here I'm benefiting that I have a strongly typed IRepository and IRepository reference, hence I can use the special methods (implemented as extension methods or by inheriting from the base interface). If I use a dynamic repository registration and retrieval method, I think I'm gonna loose this, or at least have to do some ugly castings all the time.
For the matter of DI, I would try to inject a repository factory to my real unit of work, so it can lazily instantiate the repositories.
Building on my comments above and on top of the answer here.
With a slightly modified unit of work abstraction
public interface IMyUnitOfWork
{
void CommitChanges();
void DropChanges();
IRepository<T> Repository<T>();
}
You can expose named repositories and specific repository methods with extension methods
public static class MyRepositories
{
public static IRepository<User> Users(this IMyUnitOfWork uow)
{
return uow.Repository<User>();
}
public static IRepository<Product> Products(this IMyUnitOfWork uow)
{
return uow.Repository<Product>();
}
public static IEnumerable<User> GetUsersInRole(
this IRepository<User> users, string role)
{
return users.AsQueryable().Where(x => true).ToList();
}
public static IEnumerable<Product> GetInCategories(
this IRepository<Product> products, params string[] categories)
{
return products.AsQueryable().Where(x => true).ToList();
}
}
That provide access the data as required
using(var uow = new MyUnitOfWork())
{
var allowedUsers = uow.Users().GetUsersInRole("myRole");
var result = uow.Products().GetInCategories("scarf", "hat", "trousers");
}
The way I tend to approach this is to move the type constraint from the repository class to the methods inside it. That means that instead of this:
public interface IMyUnitOfWork : IDisposable
{
IRepository<Customer> Customers { get; }
IRepository<Product> Products { get; }
IRepository<Orders> Orders { get; }
...
}
I have something like this:
public interface IMyUnitOfWork : IDisposable
{
Get<T>(/* some kind of filter expression in T */);
Add<T>(T);
Update<T>(T);
Delete<T>(/* some kind of filter expression in T */);
...
}
The main benefit of this is that you only need one data access object on your unit of work. The downside is that you don't have type-specific methods like Products.GetInCategories() any more. This can be problematic, so my solution to this is usually one of two things.
Separation of concerns
First, you can rethink where the separation between "data access" and "business logic" lies, so that you have a logic-layer class ProductService that has a method GetInCategory() that can do this:
using (var uow = new MyUnitOfWork())
{
var productsInCategory = GetAll<Product>(p => ["scarf", "hat", "trousers"].Contains(u.Category));
}
Your data access and business logic code is still separate.
Encapsulation of queries
Alternatively, you can implement a specification pattern, so you can have a namespace MyProject.Specifications in which there is a base class Specification<T> that has a filter expression somewhere internally, so that you can pass it to the unit of work object and that UoW can use the filter expression. This lets you have derived specifications, which you can pass around, and now you can write this:
using (var uow = new MyUnitOfWork())
{
var searchCategories = new Specifications.Products.GetInCategories("scarf", "hat", "trousers");
var productsInCategories = GetAll<Product>(searchCategories);
}
If you want a central place to keep commonly-used logic like "get user by role" or "get products in category", then instead of keeping it in your repository (which should be pure data access, strictly speaking) then you could have those extension methods on the objects themselves instead. For example, Product could have a method or an extension method InCategory(string) that returns a Specification<Product> or even just a filter such as Expression<Func<Product, bool>>, allowing you to write the query like this:
using (var uow = new MyUnitOfWork())
{
var productsInCategory = GetAll(Product.InCategories("scarf", "hat", "trousers");
}
(Note that this is still a generic method, but type inference will take care of it for you.)
This keeps all the query logic on the object being queried (or on an extensions class for that object), which still keeps your data and logic code nicely separated by class and by file, whilst allowing you to share it as you have been sharing your IRepository<T> extensions previously.
Example
To give a more specific example, I'm using this pattern with EF. I didn't bother with specifications; I just have service classes in the logic layer that use a single unit of work for each logical operation ("add a new user", "get a category of products", "save changes to a product" etc). The core of it looks like this (implementations omitted for brevity and because they're pretty trivial):
public class EFUnitOfWork: IUnitOfWork
{
private DbContext _db;
public EntityFrameworkSourceAdapter(DbContext context) {...}
public void Add<T>(T item) where T : class, new() {...}
public void AddAll<T>(IEnumerable<T> items) where T : class, new() {...}
public T Get<T>(Expression<Func<T, bool>> filter) where T : class, new() {...}
public IQueryable<T> GetAll<T>(Expression<Func<T, bool>> filter = null) where T : class, new() {...}
public void Update<T>(T item) where T : class, new() {...}
public void Remove<T>(Expression<Func<T, bool>> filter) where T : class, new() {...}
public void Commit() {...}
public void Dispose() {...}
}
Most of those methods use _db.Set<T>() to get the relevant DbSet, and then just query it with LINQ using the provided Expression<Func<T, bool>>.

Initializing objects using configuration file at runtime

I currently writing a project that need to generate different type of object, base on XML configuration file.
Each object that generated is instance of an IProvidor interface and and needs to contain several pre-processing, and handling methods that defined by the XML configuration file.
I generated different factories classes for:
creating the Provider (which implement the IProvider interface)
creating the Pre-Processing operation (I have IPreProcessor interface that all preProcessor class need to implement.
the same thing for handling methods (IHandler interface being implemented by several classes).
Question
How can I combine all of this into one object in runtime?
Olivier Jacot-Desc is absolutely on the right track (+1 for that). The only thing missing from his answer is loading the correct implementations from the configuration.
There are a lot of ways of doing this, for instance by storing the type name in the configuration, but you can also go for a simpler approach, such as storing a simple boolean in the configuration.
IProvider providerX = GetProviderFromConfig();
IHandler handlerZ = GetHandlerFromConfig();
IPreProcessor preProcessorY = GetProcessorFromConfig();
var provider =
new ProviderWrapper(providerX, preProcessorY, handlerZ);
private static IProvider GetProviderFromConfig()
{
if (ConfigurationManager.AppSettings["provider"] == "mail")
{
return new MailProvider();
}
else
{
return new FtpProvider();
}
}
// implement GetHandlerFromConfig just like
// the GetProvider.
UPDATE
When you have many types to switch between, storing the name of the type might be a better choice:
private static IProvider GetProviderFromConfig()
{
string typeName =
ConfigurationManager.AppSettings["provider"];
Type providerType = Type.GetType(typeName);
return (IProvider)
Activator.CreateInstance(providerType);
}
UPDATE 2
Here is an example of how to configure this with a DI Container. I'm using Simple Injector (with extensions), but any container will do (although the way to configure it will differ per container):
Registration:
using SimpleInjector;
using SimpleInjector.Extensions;
Type providerType = Type.GetType(
ConfigurationManager.AppSettings["provider"]);
Type handlerType = Type.GetType(
ConfigurationManager.AppSettings["handler"]);
Type processorType = Type.GetType(
ConfigurationManager.AppSettings["preProcessor"]);
var container = new Container();
container.Register(typeof(IProvider), providerType);
container.Register(typeof(IHandler), handlerType);
container.Register(typeof(IPreProcessor), processorType);
Resolving a provider:
var provider = container.GetInstance<IPovider>();
Tip: If you use constructor injection, you don't have to wire the types by hand, the container will do this for you. For instance, when your MailProvider looks like this, the container is able to inject the needed dependencies (IHandler, and IPreProcessor) through the constructor:
public class MailProvider : IProvider
{
private readonly IHandler handler;
private readonly IPreProcessor preProcessor;
public MailProvider(IHandler handler,
IPreProcessor preProcessor)
{
this.handler = handler;
this.preProcessor = preProcessor;
}
public void SomeAction() { ... }
}
I would create a wrapper class which implements these interfaces and inject the functionality.
Example interfaces
public interface IProvider
{
string ProvideSomething(int id);
}
public interface IPreProcessor
{
void PreProcess(string parameter);
}
public interface IHandler
{
void HandleSomething();
}
The wrapper would implement all of these interfaces
public class ProviderWrapper : IProvider, IPreProcessor, IHandler
{
private IProvider _provider;
private IPreProcessor _preProcessor;
private IHandler _handler;
public ProviderWrapper(IProvider provider, IPreProcessor preProcessor, IHandler handler)
{
_provider = provider;
_preProcessor = preProcessor;
_handler = handler;
}
#region IProvider Members
public string ProvideSomething(int id)
{
return _provider.ProvideSomething(id);
}
#endregion
#region IPreProcessor Members
public void PreProcess(string parameter)
{
_preProcessor.PreProcess(parameter);
}
#endregion
#region IHandler Members
public void HandleSomething()
{
_handler.HandleSomething();
}
#endregion
}
Now, you can instantiate a ProviderWrapper with the required functionality according to the configuration file and combine different the interface implementations.
var provider = new ProviderWrapper(providerX, preProcessorY, handlerZ);
Perhaps you could create instances of all of these classes as you would normally at runtime, then serialize them to xml. Then when you want to load your "configuration" you just need to de-serialize.
See here for serialization.

Categories

Resources