I am new to Repository Pattern and trying to use it in my project. I have following entities in my project:
UserProfile
UserTypeA
UserTypeB
UserTypeC
I have 3 types of users and UserProfile containing the general information about all three of them like Password, UserName etc. There are many other entities also and each type of user have different type of relationship with other entities. Now i have decided to create the following repository pattern for this:
public class UserProfileRepository
{
....
}
public class UserTypeAReository: UserProfileRepository
{
.....
}
public class UserTypeBReository: UserProfileRepository
{
.....
}
public class UserTypeCReository: UserProfileRepository
{
.....
}
So i want to know is this (repository inheritance) comes under good practices OR is there any other better way to do this ??
EDIT
There is a 1 to 0..1 shared primary key relationship b/w UserProfile and (UserTypeA, UserTypeB and UserTypeC).
Depending on what you're trying to achieve, you can also use an Interface or an Abstract Class.
If you want all the classes to have a common contract, but the implementation of each method is different, then you can use an Interface, and this will give more flexibility since you have multiple interface inheritance v's singe class inheritance with C#.
With the Abstract class, you can set up the methods, along with an implementation, but allow the derived class to override the base implementation.
This SO post might also help: Interface vs Base class
Related
I want to assign two classes to generic constraint at runtime using an OR condition. I don't know if it is possible or not, as I am relatively new to all this.
public interface IGenericRepository<TEntity> where TEntity : Employee Department
I want to assign TEntity either Employee class or Department class. Employee & Department are my two entities in DbContext. Please help me out on this one. Thank you in advance.
My first recommendation is: Do not use another generic repository on top of Entity Framework, because it already implements one.
In the other hand, I have seen cases where this make sense. If you are in one of those cases, consider using Generic Repository only for the things that you could apply to every single class of your model. As soon as your model object requires an special query, then create it's own repository for it.
for example, it might be that for Department you only do a ListAll(), then use a generic repository.
But let's imagine that for employee you might want to do more complex things, like ListAllEmployessUnderBossThatAreOnHolidays(Employee boss)
Then you could have this structure:
// All model classes inherit from this one
public class ModelObject
{}
public class Employee: ModelObject
{}
public class Department: ModelObject
{}
// This repository could be use for simple model objects that do simple operations
// For example, -ALL- Department operations are simple, and it never requires a
// complex query. So i handle it with this repository to avoid code duplication with
// other model objects that are also simple
public class IGenericRepository<TEntity> where TEntity : ModelObject
{ }
// Employee has some complex queries, so I create a repository for it that might or
// might not inherit from IGenericRepository
public class EmployeeRepository : IGenericRepository<Employee>
{ }
I have an application where every table requires the following methods: SelectAll, SelectSingle, SetStatus, Save.
How can I set up an interface in the DAL for that? Do I absolutely have to use generics?
Clarification:
I want to know how I can create an interface that will work for every class in my dal, or if it is possible without generic list types.
Example interface, except you have to declare a return type for the methods in the interface:
public interface IBaseDB {
public SelectAll();
public SelectOne(int id);
public void Save(object);
}
Example DAL class that implements the interface
public class UserDB : IBaseDB {
public UserCollection SelectAll() { }
public User SelectOne(int id) { }
public void Save(User user) { }
}
Bottom line: I want to have a list of required methods for each class in the DAL, but each class in the DAL has a different return type for SelectAll and SelectOne. I don't know how to accomplish this yet.
I'd recommend using generics, there aren't many reasons against this choice.
Without generics you'll have to cast instances or loosen up type checking by requiring object instances in the interface.
To better understand what you are doing, read about co- and contra-variance of .net generics.
Also, if possible, abandon completely this design (Data Access Layer, Business Logic Layer, Application and Presentation Layer) in favour of LinQ and repositories.
Some pointers:
Co/Contravariance in Generics
Repository pattern
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Interface vs Base class
Its common to see the repository pattern implemented using Interfaces
public interface IFooRepository
{
Foo GetFoo(int ID);
}
public class SQLFooRepository : IFooRepository
{
// Call DB and get a foo
public Foo GetFoo(int ID) {}
}
public class TestFooRepository : IFooRepository
{
// Get foo from in-memory store for testing
public Foo GetFoo(int ID) {}
}
But you could equally do this using abstract classes.
public abstract class FooRepositoryBase
{
public abstract Foo GetFoo(int ID);
}
public class SQLFooRepository : FooRepositoryBase
{
// Call DB and get a foo
public override Foo GetFoo(int ID); {}
}
public class TestFooRepository : FooRepositoryBase
{
// Get foo from in-memory store for testing
public override Foo GetFoo(int ID); {}
}
What are the specific advantages of using an Interface over an Abstract Class in a repository scenario?
(i.e. don't just tell me that you can implement multiple interfaces, I know this already - why would you do that in a repository implementation)
Edit to clarify - pages like "MSDN - Choosing Between Classes and Interfaces" can be paraphrased as "Choose classes over interfaces unless there is a good reason not to" - what are the good reasons in the specific case of a Repository pattern
The main advantage of using an interface over an abstract class in this instance is that an interface is entirely transparent: This is more of an issue where you don't have access to the source of the class you're inheriting from.
However, this transparency allows you to produce unit tests of a known scope: If you test a class that accepts an interface as a parameter (using the dependency injection method), you know you're testing the class with a known quantity; the testing implementation of the interface will only contain your testing code.
Similarly, when testing your repository, you know you're testing just your code in the repository. This helps to limit the number of possible variables/interactions in the test.
Personally, I tend to have an interface that holds the signature for the methods that are purely "business-related" for example Foo GetFoo(), void DeleteFood(Foo foo), etc. I also have a generic abstract class that holds protected methods like T Get() or void Delete(T obj).
I keep my methods protected in the abstract Repository class so that the outside world is not aware of the plumbery (Repository will look like object) but only of the business model via the interface.
On top of having the plumbery shared another advantage is that I have for example a Delete method (protected) available to any repository but it is not public so I am not forced to implement it on a repository where it has no business meaning to delete something from my data source.
public abstract class Repository<T>
{
private IObjectSet objectSet;
protected void Add(T obj)
{
this.objectSet.AddObject(obj);
}
protected void Delete(T obj)
{
this.objectSet.DeleteObject(obj);
}
protected IEnumerable<T>(Expression<Func<T, bool>> where)
{
return this.objectSet.Where(where);
}
}
public interface IFooRepository
{
void DeleteFoo(Foo foo);
IEnumerable<Foo> GetItalianFoos();
}
public class FooRepository : Repository<Foo>, IFooRepository
{
public void DeleteFoo(Foo foo)
{
this.Delete(foo);
}
public IEnumerable<Foo> GetItalianFoos()
{
return this.Find(foo => foo.Country == "Italy");
}
}
The advantage of using the abstract class over an interface for the plumbery is that my concrete repositories do not have to implement method they don't need (Delete or Add for example) but they are at their disposal if they need it. In the current context, there is no business reason for to some Foos so the method is not available on the interface.
The advantage of using an interface over an abstract class for the business model is that the interface provides the answers to how it make sense to manipulate Foo from a business side (does it make sense to Delete some foos? To create some? etc.). It's also easier to use this interface when Unit testing. The abstract Repository I use cannot be unit tested because it is usually tightly coupled with the database. It can only be tested in integration tested. Using an abstract class for the business purpose of my repositories would prevent me from using them in unit tests.
This is a general question that applies to any class hierarchy, not just repositories. From a pure OO point of view, an interface and a pure abstract class are the same.
If your class is part of a public API, the primary advantage of using an abstract class is that you can add methods in the future with little risk of breaking existing implementations.
Some people also like to define an interface as "something that a class can do" and a base class as "what a class is", and therefore will only use interfaces for peripheral capabilities and always define the primary function (eg. repository) as a class. I'm not sure where I stand on this.
To answer your question, I don't think there is any advantage to using an interface when it defines the primary function of the class.
While others may have more to add, from a purely practical point of view, most IoC frameworks work better with interface -> class mappings. You can have different visibilities on your interfaces & classes, whereas with inheritance, the visibilities must match.
If you're not using an IoC framework, from my point of view there is no difference. Providers are based on abstract base classes.
I guess the key difference would be, that an abstract class can contain private properties & methods, wherein an Interface cannot, as it's only a simple contract.
The result being an interface is always "no shenanigans here - what you see is what you get" whilst an abstract base class may allow side effects.
Take a look at the implementation of Tim McCarthy's Repository Framework.
< http://dddpds.codeplex.com/ >
He uses interfaces like IRepository<T> for defining the contracts, but he also uses abstract classes like RepositoryBase<T> or his SqlCeRepositoryBase < T > that implements IRepository<T>. The abstract base class is code to eliminate a lot dublicate code. A type specific repository just have to inherit frome the abstract base class and needs to add the code for its purpose. Users of the API can just code against the interface by contract.
So you can combine both approaches to use the advantages of them.
Additionally, I think most IoC-Frameworks can handle abstract classes.
Since the pattern originates in Domain Driven Design, here's a DDD answer :
The contract of a Repository is usually defined in the Domain layer. This allows objects in the Domain and Application layers to manipulate abstractions of Repositories without caring about their real implementation and the underlying storage details - in other words, to be persistence-ignorant. Besides, we often want specific behaviors to be included in the contracts of some repositories (in addition to your vanilla Add(), GetById(), etc.) so I prefer the ISomeEntityRepository form than just IRepository<SomeEntity> - we'll see why they need to be interfaces later.
The concrete implementations of Repositories, on the other hand, reside in the Infrastructure layer (or in the Tests module for test repositories). They implement the above repository contract but also have their own range of persistence-specific characteristics. For instance, if you're using NHibernate to persist your entities, having a superclass to all the NHibernate repositories with the NHibernate session and other NHibernate-related generic plumbing in it could come in handy.
Since you can't inherit several classes, one of these 2 things that your final concrete Repository inherits has to be an interface.
It's more logical for the Domain layer contract to be an interface (ISomeEntityRepository) since it's a purely declarative abstraction and mustn't make any assumption about what underlying persistence mechanism will be used - i.e. it mustn't implement anything.
The persistence-specific one can be an abstract class (NHibernateRepository or NHibernateRepository<T> in the Infrastructure layer) which allows you to centralize there some behaviors that are common to the whole range of persistent-store-specific repositories that will exist.
This results in something like :
public class SomeEntityRepository : NHibernateRepository<SomeEntity>, ISomeEntityRepository
{
//...
}
Would it be a good practice to implement entity base class like that:
[Serializable]
public abstract class Entity<T> : IComparable<Entity<T>>, IFormattable
{
public abstract Int32 CompareTo(Entity<T> entity);
public abstract String ToString(String format, IFormatProvider provider);
// ...
}
So all derived classes must implement those interfaces.
Is it reasonable to put IComparable<T> interface on entity class?
Thanks!
It's not a good (or bad) practice - it comes down entirely to your needs.
Specifying IComparable at such as general level comes with the risk that it may not make sense to compare some objects further down in the inheritance chain. Even if you can compare two objects, would it always make sense to? You may be requiring lines of code to be written to satify a contract which would never be used - beware of YAGNI circumstances.
However, this would be fine if you need to create an absolute contract so that any objects inheriting from Entity can be compared. This allows you to make positive assumptions in your code.
What would T be? Your domain class? If that's the case why not make the Entity class non-generic and directly inherit from Entity?
In general, I've found it to be a good practice to derive all domain classes that can be handled by a particular Repository from a common interface or base class. This allows the Repository to be generic to that interface, providing compile-time checking that you are attempting to use the Repository to persist something that the Repository has mapped. If you use a base class, though, don't map it unless you need a way to uniquely identify any Entity regardless of its actual subclass type; otherwise you'll get that Entity table (with any common fields) as a table in your DB and it can become difficult to manually trace through your data layer.
However, a common, mapped Entity may be desireable; you may want to uniquely identify Persons and Companies by a common ID column that is unique even through Persons and Companies are saved to different tables.
Here's a sterilized example of the hierarchy I've used in one of my projects:
//identifies a class as persistable, and requires the class to specify
//an identity column for its PK
public interface IDomainObject { long Id {get;} }
//In a repository-per-DB model, just because it's an IDomainObject doesn't mean
//a repo can work with it. So, I derive further to create basically "marker"
//interfaces identifying domain objects as being from a particular DB:
public interface ISecurityDomainObject:IDomainObject { }
public interface IDataDomainObject:IDomainObject { }
public interface IData2DomainObject:IDomainObject { }
//There may be logic in your repo or DB to prevent certain concurrency issues.
//You can specify that a domain object has the necessary fields for version-checking
//either up at the IDomainObject level, a lower level, or independently:
public interface IVersionedDomainObject:IDomainObject
{
long Version {get;}
string LastUpdatedBy {get;}
DateTime LastUpdatedDate {get;}
}
//Now, you can use these interfaces to restrict a Repo to a particular subset of
//the full domain, based on the DB each object is persisted to:
public interface IRepository<TDom> where TDom:IDomainObject
{
//yes, GTPs can be used as GTCs
T GetById<T>(long Id) where T:TDom;
void Save<T>(T obj) where T:TDom;
//not only must the domain class for SaveVersioned() implement TRest,
//it must be versionable
void SaveVersioned<T>(T versionedObj) where T:TDom, IVersionedDomainObject
}
//and now you can close TDom to an interface which restricts the concrete
//classes that can be passed to the generic methods of the repo:
public class ISecurityRepo:IRepository<ISecurityDomainObject> { ... }
If your entities require comparability and formatting than using a base class is a very good practice.
sometimes the identity field is also implemented in the base class.
I have a data provider project to access the database. this is composed by various classes (PersonDataProvider, JobDataProvider ...)
I want to create an Interface.
Do I have to create an Interface for each class?
I was tempted to create one interface and than inherit on all the classes. This involves making all the projects classes partial and change the classes name.......But i think is not the best solution.
Any suggestion?
You don't inherit an Interface you implement it. There's no need to make a class partial to add an interface to it.
An interface is a contract that the class subscribes to saying that it will honour the methods described in the interface and will implement them appropriately. For your scenario you'd create a single interface and implement it in your classes, you can then pass the instances of the various accessor classes as instances of the interface.
For example:
public interface IDataProvider
{
void LoadData();
}
The data providers would then look as follows:
public class MyDataProvder1 : IDataProvider
{
// Some methods
// Must implement LoadData
public void LoadData()
{
// Do something
}
}
public class MyDataProvder2 : IDataProvider
{
// Some methods
// Must implement LoadData
public void LoadData()
{
// Do something
}
}
You can then pass the objects as IDataProvider as follows:
IDataProvider DataProviderA = new MyDataProvider1();
IDataProvider DataProviderB = new MyDataProvider2();
// Call function that expects an IDataProvider
DoSomething(DataProviderA);
DoSomething(DataProviderB);
...
public void DoSomething(IDataProvider DataProvider)
{
DataProvider.LoadData();
}
Hopefully that clears it up for you.
I think you are approaching this incorrectly.
When you make an interface, you're making a contract for those classes. Think of it as "my class will act as a IMyInterface".
If all of your classes have a common usage scenario, then a single, common interface may be appropriate (IDataProvider, given the class names..?).
Using interface depends how you want to arrange the classes. Interface allows some sort of plug and play behaviour. So, if you need a single interface, this will mean that you shall have a single set of interfaces accross all the classes implementing the interface. In such a case, your classes PersonDataProvider, JobDataProvider etc. will have the same set of methods. If you feel, they need to be different and still be available through a single provider facade, you can think of using a facade pattern.
The facade will have interfaces for individual provider and the provider classes will implement them.
First off, I'm assuming there are standard method calls across all your xDataProvider classes. For example, instead of a SelectPerson method, you have a Select method on the PersonDataProvider class. If not, you have some work to do to make this a valid exercise.
Within Visual Studio, there is an Extract Interface refactoring option. Right-click in a xDataProvider class and choose Refactor - Extract Interface. Now name it (IDataProvider, for example) and choose the methods / properties you want in your interface, click OK and your done with this class.
Then just implement this IDataProvider interface in your other xDataProvider classes. Assuming you've already implemented similar methods in all you DataProvider classes, you won't have to write any more code (beyond the : IDataProvider).