I'm currently setting up a new project, and I have run into a few things, where I need a little input.
This is what i'm considering:
I would like a generic repository
I don't want to return IQueryable from my repository.
I would like to encapsulate my queries in specifications.
I have implemented the specification pattern
It needs to be easily testable
Now this is where I get a little stuck and my question is which way would be the most elegant way of calling the find method with one or more specifications:
(Fluent): bannerRepository.Find().IsAvailableForFrontend().IsSmallMediaBanner()
or express queries as lambdas with my specifications
(Lambda): bannerRepository.Find.Where(banner => banner.IsFrontendCampaignBanner && banner.IsSmallMediaBanner)
or maybe some completely other way? Most important thing is, that the guy implementing the MVC front, should have a good intuitive experience of the repository.
What I am hoping to achieve is to keep som flexibility with regard to being able to combine specifications, and give the experience of "filtering" with the specfications, but without leaking an IQueryable to the controller, but more like an ISpecifiable, that only allows to modify the query with specifications and not with Linq. But am i just back at leaking query logic to the controller this way?
I have seen some Fluent API's that uses Properties for specifications, so they don't add the parenthesis noise to the clients.
bannerRepository.Find.IsAvailableForFrontend.IsSmallMediaBanner.Exec()
Being Exec() a method for executing the specifications against the repo.
but even if you don't use the properties, I would go for the fluent API, since it has the minimum noise.
or maybe some completely other way?
Well, actually I don't get exactly your repository implementation (e.g. what will the method .Find() return?), but I would choose another direction:
public class Foo
{
public Int32 Seed { get; set; }
}
public interface ISpecification<T>
{
bool IsSatisfiedBy(T item);
}
public interface IFooSpecification : ISpecification<Foo>
{
T Accept<T>(IFooSpecificationVisitor<T> visitor);
}
public class SeedGreaterThanSpecification : IFooSpecification
{
public SeedGreaterThanSpecification(int threshold)
{
this.Threshold = threshold;
}
public Int32 Threshold { get; private set; }
public bool IsSatisfiedBy(Foo item)
{
return item.Seed > this.Threshold ;
}
public T Accept<T>(IFooSpecificationVisitor<T> visitor)
{
return visitor.Visit(this);
}
}
public interface IFooSpecificationVisitor<T>
{
T Visit(SeedGreaterThanSpecification acceptor);
T Visit(SomeOtherKindOfSpecification acceptor);
...
}
public interface IFooRepository
{
IEnumerable<Foo> Select(IFooSpecification specification);
}
public interface ISqlFooSpecificationVisitor : IFooSpecificationVisitor<String> { }
public class SqlFooSpecificationVisitor : ISqlFooSpecificationVisitor
{
public string Visit(SeedGreaterThanSpecification acceptor)
{
return "Seed > " + acceptor.Threshold.ToString();
}
...
}
public class FooRepository
{
private ISqlFooSpecificationVisitor visitor;
public FooRepository(ISqlFooSpecificationVisitor visitor)
{
this.visitor = visitor;
}
public IEnumerable<Foo> Select(IFooSpecification specification)
{
string sql = "SELECT * FROM Foo WHERE " + specification.Accept(this.visitor);
return this.DoSelect(sql);
}
private IEnumerable<Foo> DoSelect(string sql)
{
//perform the actual selection;
}
}
So I have an entity, its specification interface and several implementors involved in a visitor pattern, its repository interface accepting a specification interface and its repository implementation, accepting a visitor capable to translate specifications into SQL clauses (but it's just a matter of this case, of course). Finally, I would compose specification "outside" the repository interface (using fluent interface).
Maybe this is just a naive idea, but I find it quite straightforward.
Hope this helps.
Personally I would go with the lambda way. It may be because of my love for lambda but it provides lot's of space for a generic repository setup.
Considering the following:
bannerRepository.Find.Where(banner => banner.IsFrontendCampaignBanner && banner.IsSmallMediaBanner)
I don't know what your pattern looks like but you could refactor some things here:
Create a generic interface called 'IRepository' of type containing all the methods for data access.
It could look like this:
interface IRepository<T> where T : class
{
IEnumerable<T> FindAll(Func<T, bool> exp);
T FindSingle(Func<T, bool> exp);
}
Create an abstract 'Repository' class implementing this interface:
class Repository<T> : IRepository<T> where T : class
{
TestDataContext _dataContext = TestDataContext();
public IEnumerable<T> FindAll(Func<T, bool> exp)
{
_dataContext.GetTable<T>().Where<T>(exp);
}
public T FindSingle(Func<T, bool> exp)
{
_dataContext.GetTable<T>().Single(exp);
}
}
We can now create an interface for the banners table/objects which implements our 'IRepository' and a concrete class extending the abstract 'Repository' class and implementing the 'IBannerInterface':
interface IBannerRepository : IRepository<Banner>
{
}
And the matching repository to implement it:
class BannerRepository : Repository<Banner>, IBannerRepository
{
}
I would suggest using this approach as it gives you a lot of flexibility as well as enough power to control all the tiny entities you have.
Calling those methods will be super easy that way:
BannerRepository _repo = new BannerRepository();
_repo.FindSingle(banner => banner.IsFrontendCampaignBanner && banner.IsSmallMediaBanner);
Yes, it means that you have to do some work but it is hell easier for you to change the data source later on.
Hope it helps!
Related
I'm wondering if it's possible to have a decorator for 1 of multiple implemented interfaces in C#. I'm leaning towards no, but maybe.
Here's what I mean
public abstract class Auditable
{
public string CreatedBy { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime ModifiedAt { get; set; }
public string ModifiedBy { get; set; }
}
public class MyClass : Auditable
{
// <...> properties
}
public interface IWriteRepository<T> : where T : Auditable
{
T Create(T entity);
T Update(T entity);
}
public class AuditRepositoryDecorator<T> : IWriteRepository<T> where T : Auditable
{
private readonly IWriteRepository<T> _decorated;
// <...> ctor with injects
public T Create(T entity)
{
entity.ModifiedAt = time;
entity.CreatedAt = time;
entity.CreatedBy = invoker;
entity.ModifiedBy = invoker;
return _decorated.Create(entity);
}
public T Update(T entity)
{
entity.ModifiedAt = time;
entity.ModifiedBy = invoker;
return _decorated.Update(entity);
}
}
public interface IMyClassRepository : IWriteRepository<MyClass>
{
MyClass Get(int id);
}
So I would like to be able to depend on IMyClassRepository repository and whenever Create or Update would get invoked it would go through AuditRepositoryDecorator. It's a piece of logic that is executed a lot and I think it would be much simpler to have as a decorator instead of having a composition relation to some interface that does the same.
IAuditableRepository is never instantiated directly, as it's would always be implemented by another interface, so I think it might not be possible to do what I want to achieve.
I'm using the default dnc2.1 DI framework with Scrutor for decorations.
What you are trying to achieve is not possible. This isn't a limitation of the used DI Container, but rather a constraint of the .NET Type system. I often advise developers that are in DI trouble to, for the sake of understanding, remove the DI Container from the equation and instead build object graphs by hand. This works well in your situation, as I'll demonstrate below.
Assume you have an IMyClassRepository consumer:
public class RepoConsumer
{
RepoConsumer(IMyClassRepository repo) ...
}
And an IMyClassRepository implementation:
public class MyClassRepositoryImpl : IMyClassRepository
{
...
}
Now let's create the object graph for RepoConsumer that uses AuditRepositoryDecorator<MyClass>:
var repo = new MyClassRepositoryImpl();
var decoratedRepo = new AuditRepositoryDecorator<MyClass>(repo);
var consumer = new RepoConsumer(decoratedRepo); // <-- COMPILE ERROR
When you compile this code, you'll notice that the C# compiler will generate an error on the new RepoConsumer line. This is because RepoConsumer expects an IMyClassRepository. Although MyClassRepositoryImpl implements IMyClassRepository, AuditRepositoryDecorator<MyClass> does not implement IMyClassRepository.
To solve this, you might try letting AuditRepositoryDecorator<T> implement IMyClassRepository, but that will obviously be ugly, because the decorator will have to implement a dozen of interfaces, for each entity in your system.
But what this exercise proves, is that the problem is not so much with the DI Container, but rather that the type system simply not permits you to build an object graph of this. And since the type system doesn't allow you to, the DI Container certainly won't allow it. It can't work around the type checks of the type system. Fortunately.
But the solution to your problem is actually really straightforward: remove the specific IMyClassRepository and let consumers depend on IWriteRepository<MyClass> instead. This might seem a disappointing solution, but there is a myriad of problems surrounding deriving from generic interfaces. Just accept the fact that consumers depend on such generic abstraction. It takes some time, but eventually, you will start to love and appreciate this style of programming.
But, of course, this still leaves us with the question of how to add new methods, such as MyClass Get(string). There are multiple solutions, such as:
Implement it as extension method (only possible when the method itself requires access to the interface itself, not to the class's internals)
Define a separate interface, which might be a good idea in general, according to the Interface Segregation Principle
the most used approach in these cases is the repository pattern as explained here in my answer: How do I avoid code repetition when defining a class of functions that only vary the data type of the parameters they handle?
in your case this is the classes hierarchy:
public interface IWriteRepository<T> : where T : Auditable
{
T Create(T entity);
T Update(T entity);
}
public abstract class WriteRepositoryBase<T> : IWriteRepository<T> where T : Auditable
{
//implement create and update
}
public interface IMyRepository : IWriteRepository<MyClass>
{
MyClass Get(string id);
}
public class MyRepository : WriteRepositoryBase<MyClass>, IMyRepository
{
//implement Get
}
I am looking at the Respository Pattern in Microsoft website.
Respository Pattern
I section i am not understand what IAggregateRoot does?
public interface IRepository<T> where T : IAggregateRoot
{
//....
}
Can each respository class interact each others e.g. Product respository may be used by OrderRespository.
TL;DR:
The IAggregateRoot interface doesn't really do anything except mark classes that are aggregate roots so that if a class doesn't implement that interface,
public class Repository<NotARootAggregate> : IRepository<NotARootAggregate>
...won't compile. It helps us not to create a repository for a class that isn't an aggregate root.
That generic constraint is just a way of preventing the creation of repository for something that isn't an aggregate root.
What is an aggregate root and why does it matter when we're creating a repository? Here's a really contrived example:
public interface IAggregateRoot { }
public enum TreeType
{
Apple, Lemon
}
public class Fruit
{
public Fruit(TreeType fruitType) { FruitType = fruitType; }
public TreeType FruitType { get; }
}
public class TreeBranch
{
private List<Fruit> fruitOnBranch = new List<Fruit>();
public TreeBranch(TreeType branchType) { BranchType = branchType; }
public TreeType BranchType { get; }
public void AddFruit(Fruit fruit)
{
if (fruit.FruitType != BranchType)
{
throw new ArgumentException("Wrong type of fruit!");
}
fruitOnBranch.Add(fruit);
}
}
public class Tree : IAggregateRoot
{
private List<TreeBranch> branches = new List<TreeBranch>();
public Tree(TreeType treeType) { TreeType = treeType; }
TreeType TreeType { get; }
public void AddBranch(TreeBranch branch)
{
if(branch.BranchType != TreeType)
{
throw new ArgumentException("Wrong type of branch!");
}
branches.Add(branch);
}
}
It's designed so that it's impossible to add the wrong kind of branch to a tree or the wrong kind of fruit to a branch. So it's impossible to add a lemon to an apple tree. It's also impossible to change a lemon into an apple. The code enforces the rule that the right fruit grows on the right tree.
Having the tree as the aggregate root means that we're only going to save the tree to the database along with its branches and fruit. We'll never save just the branches or fruit. As long as we enforce that, we won't accidentally add lemons to apple trees.
If we defined a FruitRepository then we could accidentally go around that and save incorrect fruit.
So declaring the repository with that generic constraint:
public interface IRepository<T> where T : IAggregateRoot
^^^^^^^^^^^^^^^^^^^^^^^^
means that a class that implements the interface won't compile unless T implements IAggregateRoot.
So the only purpose of IAggregateRoot is to mark a class and say, "This is an aggregate root. It's okay to define a repository for it." That's why the documentation you referenced calls it a "marker interface."
It's a little bit weird because you could just put that interface on Fruit or TreeBranch, and then you'd be able to create a repository for them. Nothing will stop you from doing that. But the idea is that you or someone else will know not to do that. (But if you already knew not to do that, then you didn't need the IAggregateRoot interface to stop you from creating the repository, right?) So it's a slightly weak guard against making a mistake.
I have two interfaces implemented by one main class. How can i refactor my code in a way that on implementing each contract, the methods of each contract has a different value for a parameter such as DatabaseName.
Example :
Class1 Implements Interface1,Interface2
Interface1.GetData() has DatabaseName set to Database 1
Interface2.GetData() has DatabaseName set to Database 2
I can configure those value in the methods GetData() but i want a cleaner way of doing it.
Any pattern recommendation be that DI ,Domain driven ,even basic inheritance example which accomplishes the above is what i am looking for.
It sounds like all you need is explicit interface implementation:
public class Class1 : Interface1, Interface2
{
// Note the lack of access modifier here. That's important!
Data Interface1.GetData()
{
// Implementation for Interface1
}
Data Interface2.GetData()
{
// Implementation for Interface2
}
}
Obviously the two methods can call a common method with a parameter to specify the database name or similar.
Refactoring is usually motivated by noticing a code smell and the very fact that you ended up in a situation where you have to implement 2 abstraction which expose similar functionality is the code smell.
Without having more understanding of the problem I might not be able to provide you a conclusive answer but with limited understanding this is what I would propose. Have 2 different concrete implementation each implementing one interface and have a factory which would be injected to client and make the client make the deliberate decision which one of these implementation is needed. In case these concrete classes share common functionality you can always abstract that into a common parent class.
public interface ISQLReader
{
string GetData();
}
public interface IOracleReader
{
string GetData();
}
public abstract class Reader
{
protected void CommonFunctionaility()
{
}
}
public class MSSQLReader : Reader, ISQLReader
{
public string GetData()
{
return "MSSQL";
}
}
public class OracleReader : Reader, IOracleReader
{
public string GetData()
{
return "Oracle";
}
}
public interface IReaderFactory
{
OracleReader CreateOracleReader();
MSSQLReader CreateMSSQLReader();
}
public class ReaderFactory : IReaderFactory
{
public MSSQLReader CreateMSSQLReader() => new MSSQLReader();
public OracleReader CreateOracleReader() => new OracleReader();
}
public class ReaderClient
{
private IReaderFactory _factory;
public ReaderClient(IReaderFactory factory)
{
this._factory = factory;
}
}
Explicit interface implementation is technique that should restrict usage of the functionality until the client has made and explicit cast there by making a deliberate decision.
I would like to design a domain model using internal interfaces
and then create restricted public interfaces (for users of the assembly)
Whilst this is possible in CSharp I keep running into messy code related to parallel interfaces:
public interface IAccount { IList<ITran> Transactions { get; } }
internal interface IAccountInternal : IAccount { IList<ITranInternal> Transactions { get; } }
internal class Account : IAccountInternal { }
here the implementation of Account gets very messy as there are many collections which need dual interfaces etc.
Furthermore I would like to guarantee that the public interfaces are implemented using the internal interfaces (as opposed to directly accessing the concrete classes)
This must be a common scenario, can anybody recommend a clean approach?
using generic interface covariance in dot net 4.0 I managed to clean things up (note the "out" modifier on the T parameter)
public interface IListReadOnly<out T> : IEnumerable<T> {
int Count { get; }
T this[int index] { get; }
}//class
this lets me return collections of internal objects typed as public objects because:
public interface IPublic { }
internal interface IPrivate : IPublic { }
now this works:
private IListReadOnly<IPrivate> list = ...
public IListReadOnly<IPublic> List { get { return list; } }
This seems like a bad idea, that model seems to be very complex.
My first thought is to reduce the need for internal interfaces. If you're using them for the purpose of unit testing, then I'd recommend only testing the external (public) interface, and essentially forgoing the use of internal interfaces altogether.
Other than that, if you can elaborate on the need for the internal domain model it might help others answer your question better.
In what scenarios would somebody pass (or receive) an interface as a parameter? Is it really a useful thing or just a fancy way of doing something?
It's an extremely useful thing.
Take any of the LINQ extension methods, for instance. They don't care what's passed to them, as long as it implements IEnumerable<T>. The idea is that they can all be applied to anything that you can enumerate over using a foreach loop.
Imagine how pointlessly restrictive it would be if they all required you to pass T[] arrays, or List<T> objects, for example.
Here's just one very trivial illustration. Let's pretend the LINQ extensions don't exist (which is actually a real possibility if I'm using .NET 2.0) and I want to write a Sum method.
I could write it like this:
public static double Sum(List<double> values)
{
double sum = 0.0;
foreach (double value in values)
{
sum += value;
}
return sum;
}
That's all well and good, but notice something here: I wrote the method to take a List<double>, which is a class that has far more functionality than this code depends on. Where does it use Insert? Where does it use RemoveAt? FindAll? Sort? Nope, none of that is required. So is it really necessary that this method get passed a List<double>?
Moreover, say I have a double[]. Theoretically, I should be able to pop that right in as the values parameter, since all I'm doing is enumerating over it using a foreach; but since I've typed values as List<double>, to pass a double[] to my Sum method I'd have to do this:
double sum = Sum(new List<double>(myArray));
That's just a completely unnecessary new object I've constructed simply to call code that really should've been able to handle my original object in the first place.
By writing methods that take interfaces as parameters, you make your code more flexible and more powerful, and you avoid imposing inappropriate restrictions (give me an X, even though I could just as easily do this with a Y) on calling code.
The easiest way to remember, is that it's all about programming to the interface, not the implementation. Say for instance, I have a method where I want to do something, e.g.
public void MakeNoise(IAnimal animal)
{
animal.MakeNoise();
}
I don't care what the specific implementation is, I just know that whatever is passed in, I can call MakeNoise(). I program to an interface, not an implementation.
public class Dog : IAnimal
{
public void MakeNoise()
{
Console.WriteLine("Woof");
}
}
public class Cat : IAnimal
{
public void MakeNoise()
{
Console.WriteLine("Meow");
}
}
Interface programming is a core aspect of OOP, you'll find them incredibly useful.
Whenever you need abstraction.
One good example is the IEnumerable<T> and IQueryable<T> interfaces in the .NET Framework. They allow you to write Extension Methods that can be used against List<T>, Dictionary<TKey, TValue>, or even T[].
You could also take Dependency Injection for example. In ASP.NET MVC, it is common to use Repositories for Data Access:
public class MyClassRepository
{
public MyClass GetById(int id)
{
// Some Implementation
}
}
public class MyController
{
private MyClassRepository _repo;
public class MyController() : base(new MyClassRepository()) { }
public class MyController(MyClassRepository repo) { _repo = repo; }
}
Now, if you want to Mock that Repository for Unit Testing...you're boned. There's no easy way. In comes Interfaces!
public interface IMyClassRepository
{
public MyClass GetById(int id);
}
public class MyClassRepository : IMyClassRepository
{
public MyClass GetById(int id)
{
// Some Implementation
}
}
public class MyController
{
private IMyClassRepository _repo;
public class MyController() : base(new MyClassRepository()) { }
public class MyController(IMyClassRepository repo) { _repo = repo; }
}
Now with the introduction of an Interface, we are free to mock IMyClassRepository however we see fit for testing purposes. Usually this involves a simple mock object with specified behavior to product reliable results.
Interfaces are very useful.
They help with decoupling your code - for example, if you use the IList interface and pass that in to your method and use it in your method, you can pass in any collection that implements this interface, whether it is in the BCL or not.
One area where interfaces would make good sense is if you are using a design pattern approach.
For instance, the Observer pattern, or the Proxy pattern, the Visitor pattern, and others. You probably could choose not to use an interface, but I'd imagine that you'll quickly decide that the code becomes much cleaner (as in more modular, concerns-separated) than a non-interfaced code. It just helps promote better code, in these situations.
Polymorphism!
They help you write code that doesn't discriminate against certain classes just because they don't inherit from a special base class. Your functions will be equal-opportunity executors.