how is repository pattern really done? - c#

I'm using elastic search with my asp.net core web api. I don't quite get where the line is drawn when it comes to repository responsibility.
Here is how I have defined my implementations:
public SearchRespository: ISearchRespository<Product>
{
private ElasticClient _client
public async Task<ISearchResponse<Product>> SearchAsync(ISearchRequest request)
{
var response = _client.SearchAsync<Product>(request);
return await products;
}
. . . // others
}
In my controller:
public SearchController : Controller
{
private ISearchRespository _repo;
public SearchController(ISearchRespository repo)
{
_repo = repo;
}
public async Task<IActionResult> Search()
{
// build my search request from Request.Query
var response = await _client.SearchAsync(request);
var model = new SearchModel
{
Products = response.Documents;
Aggregations = response.Aggregations;
}
return Ok(model)
}
As it stands the repo is passing the elastic response as is. My question is have I drawn my line right? what if I just move _client to my controller or move building request and constructing model to _repo? how do you guys get your repository right?

The fact that you use Elastic Search should be an implementation detail that especially the controller shouldn't know about, so you are absolutely right in abstracting this away from the controller. I often look at the SOLID principles to get a sense whether I'm on the right track or not. If we look at the Dependency Inversion Principle, you'll see that it guides us towards a style that is also known as Ports and Adapters, which basically means that the use of an external tool is abstracted away (the port), and on the boundary of the application you implement an Adapter that connects to that third party.
So from the sense of the Dependency Inversion Principle, you're on the right track.
There is however a lot of misunderstanding of what Martin Fowler's Repository Pattern is trying to solve. The definition is as follows:
Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.
Important to note here is that a repository is intended to be used by the domain layer.
There is however a lot of misuse of the repository pattern, because many developers start to use it as a grouping structure for queries. The repository is -as I see it- not intended for all queries in the system; but only for queries that are the domain needs. These queries support the domain in making decisions for the mutations on the system.
Most queries that your system requires however are not this kind of query. Your code is a good example, since in this case you skip the domain completely and only do a read operation.
This is something that is not suited for the repository. We can verify this by comparing it with the SOLID principles again.
Let's say we have the following repository interface:
public interface IUserRepository
{
User[] FindUsersBySearchText(string searchText, bool includeInactiveUsers);
User[] GetUsersByRoles(string[] roles);
UserInfo[] GetHighUsageUsers(int reqsPerDayThreshold);
// More methods here
}
This is a typical repository abstraction that you'll see developers write. Such abstraction is problematic from perspective of the SOLID principles, because:
The Interface Segregation Principle is violated, because the interfaces are wide (have many methods) and consumers of those interfaces are forced to depend on methods that they don’t use.
The Single Responsibility Principle is violated, because the methods in the repository implementation are not highly cohesive. The only thing that relates those methods is the fact that they belong to the same concept or entity.
The design violates the Open/Closed Principle, because almost every time a query is added to the system, an existing interface and its implementations need to be changed. Every interface has at least two implementations: one real implementation and one test implementation.
A design like this also causes a lot of pain down the road, because it becomes hard to apply cross-cutting concerns (like security, auditing, logging, caching, etc) down the line.
So this is not something the Repository pattern is intended to solve; such design is just a big SOLID violation.
The solution here is to model queries separately in your system and not use a repository at all. There are many articles written about this, and you can read my take on this here.
If I look at your design, it actually has some resemblance with the design I'm promoting here, since you seem to have a generic query method that can handle many type of queries. The query message (your ISearchRequest) seems however specific to Elastic Search. This is something you should strive to prevent, as the Dependency Inversion Principle states.

Related

How do I deal with two situations that could be candidates for a strategy pattern solution?

I am designing a client that will call methods based on certain inputs. I will be sending in a billing system enum and calling an endpoint to determine which billing system is appropriate for an existing patient. Once I get the billing system, I have to check to see what type of operation I need to perform and make an API call based on the billing system.
For example, if I need to update a patient record and the patient is in BillingSystemA, I need to call a PUT-based method of the API for BillingSystemA.
I need to have CRUD methods for each billing system.
Selecting between the two billing systems and allowing for future growth made me think that the strategy pattern was a good fit. Strategy seems to work for the billing system, but what about the CRUD operations?
I have a BillingStrategy abstract class that has Create, Update, Get and Delete methods, but I need those methods to work against a variety of types. Can I just make the methods generic, like T Create<T> or bool Update<T> or do I need a strategy within a strategy to manage this? I've analyzed myself into a corner and could use some advice.
Here's a rough illustration. I invented a lot of the specifics, and the names aren't so great. I tend to revisit names as I refactor. The main point is to illustrate how we can break up the problem into pieces.
This assumes that there are classes for Patientand Treatment and an enum for InsuranceType. The goal is to bill a patient for a treatment, and determine where to send the bill based on the patient's insurance.
Here's a class:
public class PatientBilling
{
private readonly IBillingHandlerByInsuranceSelector _billingHandlerSelector;
private readonly IBillingHandler _directPatientBilling;
public PatientBilling(
IBillingHandlerByInsuranceSelector billingHandlerSelector,
IBillingHandler directPatientBilling)
{
_billingHandlerSelector = billingHandlerSelector;
_directPatientBilling = directPatientBilling;
}
public void BillPatientForTreatment(Patient patient, Treatment treatment)
{
var billingHandler = _billingHandlerSelector.GetBillingHandler(patient.Insurance);
var result = billingHandler.BillSomeone(patient, treatment);
if (!result.Accepted)
{
_directPatientBilling.BillSomeone(patient, treatment);
}
}
}
and a few interfaces:
public interface IBillingHandler
{
BillSomeoneResult BillSomeone(Patient patient, Treatment treatment);
}
public interface IBillingHandlerByInsuranceSelector
{
IBillingHandler GetBillingHandler(InsuranceType insurance);
}
As you can see this will rely heavily on dependency injection. This class is simple because it doesn't know anything at all about the different insurance types.
All it does is
Select a billing handler based on the insurance type
try to submit the bill to the insurance
if it's rejected, bill the patient
It doesn't know or care how any of that billing is implemented. It could be a database call, an API call, or anything else. That makes this class very easy to read and test. We've deferred whatever isn't related to this class. That's going to make it easier to solve future problems one at a time.
The implementation of IBillingHandlerByInsuranceSelector can be an abstract factory that will create and return the correct implementation of IBillingHandler according to the patient's insurance. (I'm glossing over that but there's plenty of information on how to create abstract factories with dependency injection containers.)
In a sense we could say that the first part of this problem is solved (although we're likely to refactor some more.) The reason why is that we can write unit tests for it, and any of the work specific to one insurance type or another will be in different classes.
Next we can write those insurance-specific implementations. Suppose one of the insurance types is WhyCo, and now we need to create an IBillingHandler for them. We're essentially going to repeat the same process.
For the sake of illustration, let's say that submitting a bill to WhyCo is done in two steps. First we have to make a request to check eligibility, and then we have to submit the bill. Maybe other insurance APIs do this in one step. That's okay, because no two implementations have to have anything in common with each other. They just implement the interface.
At this point we're dealing with the specifics of one particular insurance company, so somewhere in here we'll need to convert our Patient and Treatment information into whatever data they expect to receive.
public class WhyCoBillingHandler : IBillingHandler
{
private readonly IWhyCoService _whyCoService;
public WhyCoBillingHandler(IWhyCoService whyCoService)
{
_whyCoService = whyCoService;
}
public BillSomeoneResult BillSomeone(Patient patient, Treatment treatment)
{
// populate this from the patient and treatment
WhyCoEligibilityRequest eligibilityRequest = ...;
var elibility = _whyCoService.CheckEligibility(eligibilityRequest);
if(!elibility.IsEligible)
return new BillSomeoneResult(false, elibility.Reason);
// create the bill
WhyCoBillSubmission bill = ...;
_whyCoService.SubmitBill(bill);
return new BillSomeoneResult(true);
}
}
public interface IWhyCoService
{
WhyCoEligibilityResponse CheckEligibility(WhyCoEligibilityRequest request);
void SubmitBill(WhyCoBillSubmission bill);
}
At this point we still haven't written any code that talks to the WhyCo API. That makes WhyCoBillingHandler easy to unit test. Now we can write an implementation of IWhyCoService that calls the actual API. We can write unit tests for WhyCoBillingHandler and integration tests for the implementation of IWhyCoService.
(Perhaps it would have been better if translating our Patient and Treatment data into what they expect happened even closer to the concrete implementation.)
At each step we're writing pieces of the code, testing them, and deferring parts for later. The API class might be the last step in implementing WhyCo billing. Then we can move on to the next insurance company.
At each step we also decide how much should go into each class. Suppose we have to write a private method, and that method ends up being so complicated that it's bigger than the public method that calls it and it's hard to test. That might be where we replace that private method with another dependency (abstraction) that we inject into the class.
Or we might realize up front that some new functionality should be separated into its own class, and we can just start off with that.
The reason why I illustrated it this way is this:
I've analyzed myself into a corner
It's easy to become paralyzed when our code has to do so many things. This helps to avoid paralysis because it continually gives us a path forward. We write part of it to depend on abstractions, and then that part is done (sort of.) Then we implement those abstractions. The implementations require more abstractions, and we repeat (writing unit tests all the way in between.)
This doesn't enforce best practices and principles, but it gently guides us toward them. We're writing small, single-responsibility classes. They depend on abstractions. We're defining those abstractions (interfaces, in this case) from the perspective of the classes that need them, which leads to interface segregation. And each class is easy to unit test.
Some will point out that it's easy to get carried away with all the abstractions and create too many interfaces and too many layers of abstraction, and they are correct. But that's okay. At every single step we're likely to go a little off balance one way or the other.
As you can see, the problems that occur when we have to deal with the difference between billing systems becomes simpler. We just create every implementation differently.
Strategy seems to work for the billing system, but what about the CRUD operations?
The fact that they all have different CRUD operations is fine. We've made components similar where they need to be similar (the interfaces through which we interact with them) but the internal implementations can be as different as they need to be.
We've also sidestepped the question of which design patterns to use, except that IBillingHandlerByInsuranceSelector is an abstract factory. That's okay too, because we don't want to start off too focused on a design pattern. If this was a real application, I'd assume that a lot of what I'm doing will need to be refactored. Because the classes are small, unit tested, and depend on abstractions, it's easier to introduce design patterns when their use becomes obvious. When that happens we can likely isolate them to the classes that need them. Or, if we've just realized that we've gone in the wrong direction, it's still easier to refactor. Unless we can see the future that's certain to happen.
It's worth taking some time up front to understand the various implementation details to make sure that the way you have to work with them lines up with the code you're writing. (In other words, we still need to spend some time on design.) For example, if your billing providers don't give you immediate responses - you have to wait hours or days - then code that models it as an immediate response wouldn't make sense.
One more benefit is that this helps you to work in parallel with other developers. If you've determined that a given abstraction is a good start for your insurance companies and maybe you've written a few, then it's easy to hand off other ones to other developers. They don't have to think about the whole system. They can just write an implementation of an interface, creating whatever dependencies they need to.

Repository pattern - make it testable, DI and IoC friendly and IDisposable

What I have:
public interface IRepository
{
IDisposable CreateConnection();
User GetUser();
//other methods, doesnt matter
}
public class Repository
{
private SqlConnection _connection;
IDisposable CreateConnection()
{
_connection = new SqlConnection();
_connection.Open();
return _connection;
}
User GetUser()
{
//using _connection gets User from Database
//assumes _connection is not null and open
}
//other methods, doesnt matter
}
This enables classes that are using IRepository to be easily testable and IoC containers friendly. However someone using this class has to call CreateConnection before calling any methods that are getting something from database, otherwise exception will be thrown. This itself is kind of good - we dont want to have long lasting connections in application. So using this class I do it like this.
using(_repository.CreateConnection())
{
var user = _repository.GetUser();
//do something with user
}
Unfortunetelly this is not very good solution because people using this class (including even me!) often forget to call _repository.CreateConnection() before calling methods to get something from database.
To resolve this I was looking at Mark Seemann blog post SUT Double where he implements Repository pattern in correct way. Unfortunately he makes Repository implement IDisposable, which means I cannot simply inject it by IoC and DI to classes and use it after, because after just one usage it will be disposed. He uses it once per request and he uses ASP.NET WebApi capabilities to dispose it after request processing is done. This is something I cannot do because I have my classes instances which use Repository working all the time.
What is the best possible solution here? Should I use some kind of factory that will give me IDisposable IRepository ? Will it be easily testable then?
There are a few problematic spots in your design. First of all, your IRepository interface implements multiple levels of abstractions. Creating a user is a much higher level concept than connection management. By placing these behaviours together you are breaking the Single Responsibility Principle which dictates that a class should only have one responsibility, one reason to change. You are also violating the Interface Segregation Principle that pushes us toward narrow role interfaces.
On top of that, the CreateConnection() and GetUser method are temporal coupled. Temporal Coupling is a code smell and you are already witnessing this to be a problem, because you are able to forget the call to CreateConnection.
Besides this, the creation of the connection is something you will start to see on every repository in the system and every piece of business logic will need to either create a connection, or get an existing connection from the outside. This becomes unmaintainable in the long run. Connection management however is a cross-cutting concern; you don't want the business logic to be concerned in such low level concern.
You should start by splitting the IRepository into two different interfaces:
public interface IRepository
{
User GetUser();
}
public interface IConnectionFactory
{
IDisposable CreateConnection();
}
Instead of letting business logic manage the connection itself, you can manage the transaction at a higher level. This could be the request, but this might be too course grained. What you need is to start the transaction somewhere in between the presentation layer code and the business layer code, but without having to having to duplicate yourself. In other words, you want to be able to transparently apply this cross-cutting concern, without having to write it over and over again.
This is one of the many reasons that I started to use application designs as described here a few years ago, where business operations are defined using message objects and their corresponding business logic is hidden behind a generic interface. After applying these patterns, you will have a very clear interception point where you can start transactions with their corresponding connections and let the whole business operation run within that same transaction. For instance, you can use the following generic code that can be applied around every piece of business logic in your application:
public class TransactionCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
{
private readonly ICommandHandler<TCommand> decorated;
public TransactionCommandHandlerDecorator(ICommandHandler<TCommand> decorated) {
this.decorated = decorated;
}
public void Handle(TCommand command) {
using (var scope = new TransactionScope()) {
this.decorated.Handle(command);
scope.Complete();
}
}
}
This code wraps everything around a TransactionScope. This allows your repository to simply open and close a connection; this wrapper will ensure that the same connection is used nonetheless. This way you can inject an IConnectionFactory abstraction into your repository and let the repository directly close the connection at the end of its method call, while under the covers .NET will keep the real connection opened.
Create a repository factory that creates IDisposable repositories.
public interface IRepository : IDisposable {
User GetUser();
//other methods, doesn't matter
}
public interface IRepositoryFactory {
IRepository Create();
}
You create them within a using and they are disposed of when done.
using(var repository = factory.Create()) {
var user = repository.GetUser();
//do something with user
}
You can inject the factory and create the repositories as needed.
So, you already mentioned that
we dont want to have long lasting connections in application
which is absolutely right!
You need to open connection in each repository method implementation, execute queries or commands against the database, and then close the connection. I don't see why you would expose anything like connection to the domain layer. In other words, remove CreateConnection() methods from repositories. They are not needed. Each method will open/close it inside, when implemented.
There are times when you would want to wrap several repository method calls into something, but that is only related to transaction, not connection. In that case there are 2 answers:
Check the correctness of your Repository pattern implementation. You should have repositories only for Aggregate Roots. Not every entity qualifies as aggregate root. Aggregate root is the guaranteed transaction boundary, so you should not be worried about transactions anyway out of repository - each repository method call will naturally follow the boundary, since it handles only a single aggregate root at a time.
If you still need to execute operations against several aggregate roots in one go, then you will have to implement a pattern called Unit of Work. This is essentially a business layer transaction implementation. I don't recommend relying on built-in transaction features into storage technologies for this specific case (several aggregates in one go), because they differ from vendor to vendor (while relational DBs can guarantee several aggregate roots in one go, NoSQL DBs only guarantee single aggregate at a time).
From my experience, you should only need to modify single aggregate at a time. Unit of Work is a very rare case pattern. So, just rethink your repositories and aggregate roots, that should do the trick for you.
Just for the completeness of the answer - you do need to have repository interfaces, which you already have. Thus, your approach is already unit-testable.
You are mixing apples with oranges and peaches.
There are three concepts at play here:
The repository contract
The implementation details
Repository lifetime management
Your repository conceptually holds users, but it has a CreateConnection() method that indicates details of the implementation (a connection is needed). Not good.
What you need to do is remove the CreateConnection() method from the interface. Now you have a true definition of what a user repository is (by the way, you should call it that, IUserRepository).
On to the implementation details:
You have a user repository that talks to a database, so you should implement a DatabaseUserRepository class. This is where the details of creating a connection and handling it are stored. You may decide to keep an open connection for the lifetime of the object, or you may decide it's best to open and close a connection for every operation.
On to the lifetime of the object:
You have a dependency container. You may have decided you want your repository to be used as a singleton because your DatabaseUserRepository class implements atomic, thread-safe operations, or you may want your repository to be transient so a new instance is created because it implements a unit of work pattern which means that all changes are saved together (e.g. EF.SaveChanges()).
See the difference now?
The interface allows for unit testing. Any component that needs data from the database can use a mock repository that loads garbage from memory (e.g. MemoryUserRepository).
The implementation provides a repository that stores users in a database. You may even decide to have two versions of this class that implement the interface along with different strategies or patterns.
The lifetime of the repository will be setup according to the implementation details in the dependency container.
I would create a Connection Factory...
public class ConnectionFactory
{
public IDbConnection Create()
{
// your logic here
}
}
Now make it a dependency to your repositories, and use it inside you repositories as well... You don`t need an IDisposable repository, you need to dispose the connection.
I'm on the cellphone, so it's hard to give you a more detailed example. If you need, i can edit it later with a more detailed example.

Dbcontext class simple interpretation

would anybody interpret it into simple words as i'm newbie to MVC and can't understand this clearly.
A DbContext instance represents a combination of the Unit Of Work and
Repository patterns such that it can be used to query from a database
and group together changes that will then be written back to the store
as a unit. DbContext is conceptually similar to ObjectContext.
Source: http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.113).aspx
Unit of work and Repository are patterns for dealing with data(irrespective of if it is a database or any other storage(may be List<T> objects even)) and usually implemented while dealing with data from a database.
It only means that Entity framework internally has these two patterns implemented. To understand it better, just google for Repository Patterns and Unit of work pattern which usually go hand in hand.
If you still do not get the meaning, don't worry - until you know how to work with Entity Framework(Code First is extremely easy to understand, once you understand Linq) the understanding of pattern is not important. Refer back to the same article once you have more experience with the patterns of dealing with data. You only require a little more experience to appreciate them.
Examples of these two patterns are better described by the two interfaces:
interface IHomesRepository {
List<Home> GetAllHomes();
Home GetHomeById(int id);
void AddHome(Home home);
void UpdateHome(int id, Home home);
void DeleteHome(Home home);
}
interface IUnitOfWork : IDisposable{
IHomesRepository repository {get;}
// more repositories, if required
void Commit();
}
this is a good example to understand the unit of work and the repository pattern, i suggest you to read it until the end :
http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

Dependency Injection - What to do when you have a lot of dependencies?

I have a class A that depends on 10 other classes. According to Dependency Injection pattern, i should pass all dependencies of A by its constructor.
So lets assume this constructor (of course this is not a working or real code, since I am not allowed to post the real code here)
public ClassA(ClassB b, ClassC c, ClassD d, ClassE e, ClassF f, ClassG g, ClassH h, ClassI i) {
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
this.g = g;
this.h = h;
this.i = i;
}
I have read on Martin Fowler's book about refactoring that having a method with a lot of parameters is a code smell and should not happen.
My question is: is this OK when we are talking about DI? Is there a better way of inject dependencies without breaking Martin Fowler's rules?
I know I could pass the dependencies through properties, but that may cause errors since no one is really sure what should be pass in order that the class works.
EDIT
Thanks for all your answers. I will try now to demonstrate some of class A dependencies:
1 - A class to access a DB
2 - Another class to access another DB (yes, i need to perform operations on two databases)
3 - A class to send error notifications by email
4 - A class to load configurations
5 - A class that will act as timer for some operations (maybe this one can be avoided)
6 - A class with business logic
There any many others that i am trying to get rid of, but those are really necessary and I dont see any ways of avoiding them.
EDIT
After some refactoring now i have 7 dependencies (down from 10). But I have 4 DAO objects:
CustomerDAO
ProcessDAO
ProductsDAO
CatalogDAO
Is it correct do create another class called MyProjectDAO and inject those DAOS onto it? This way I will have only one DAO class that aggregates all DAO objects of my project. I dont think this is a good idea because it violates the Single Responsibility Principle. Am I right?
In my experience:
Try to design your class so it needs fewer dependencies. If it needs that many, it may have too many responsibilities.
If you're really convinced that your class design is appropriate, consider whether it may make sense for some of those dependencies to be joined together (e.g. via an adapter which takes responsibility for one "big" operation your class needs by delegating to a few of the dependencies). You can then depend on the adapter instead of the "smaller" dependencies.
If every other bit really makes sense, just swallow the smell of having a lot of parameters. It happens sometimes.
Can you justify (to yourself) why the class depends on 10 other classes? Are there member variables you use to tie together a subset of those classes? If so, that indicates that this class should be broken up so that the extracted class would depend on the subset and the variables that tie such state together goes in the extracted class. With 10 dependencies, it's possible that this class has simply grown too large and needs to have its internals broken up anyway.
A note regarding your final sentence: such order dependency can also be a code smell, so it's probably good not to expose it in your interface. In fact, consider whether or not the order requirements are because operations need to be carried out in a specific order (it is the complexity of the algorithm or protocol), or because you've designed your classes to be inter-dependent. If the complexity is due to your design, refactor to eliminate the ordered dependency where possible.
If you cannot refactor (the complexities are all essential and you just have a terrible coordination problem on your hands), then you can abstract the ugliness and keep users of this class shielded (builder, factory, injector, etc).
Edit: Now that I have thought about it, I am not convinced that essential complexities of your algorithm or protocol cannot be abstracted a bit (though that might be the case). Depending on your specific problem, similarities in the manipulations of those dependent classes might either be better solved with the Strategy pattern or the Observer pattern (event listeners). You might have to wrap these classes in classes that adapt them to slightly different interfaces than what they currently expose. You'd have to evaluate the tradeoff of having the code in this monster class become more readable (yay) at the expense of up to 10 more classes in your project (boo).
I'd also like to make an addendum to abstracting the construction of this class. It seems important that any class that depends on this class also use the Dependency Injection pattern. That way, if you do use a builder, factory, injector, etc. you don't accidentally rob yourself of some of the benefits of using the DI pattern (the most important in my mind is the ability to substitute mock objects for testing).
Edit 2 (based on your edit):
My first thought is "what, no logging dependency?" :)
Even knowing what the dependencies are, it's difficult to offer useful advice.
First: what are the responsibilities of everyone? Why does this class depend on controller code (the business logic) and on Model code (two different database access classes, with DAO classes)?
Depending both on DAOs and DB access classes is a code smell. What is the purpose of a DAO? What is the purpose of the DB classes? Are you trying to operate at multiple levels of abstraction?
One of the principles of OO is that data and behavior get bundled into little things called classes. Have you violated this when you created this business logic class distinct from the objects it manipulates distinct from the DAO distinct from this class? Related: Take a brief diversion into SOLID.
Second: A class to load configurations. Smells bad. Dependency Injection helps you identify dependencies and swap them out. Your monster class that depends on certain parameters. These parameters are grouped into this configuration class because...? What is the name of this configuration class? Is it DBparameters? if so, it belongs to the DB object(s), not to this class. Is it generic like Configurations? If so, you've got a mini dependency injector right there (granted, it is probably only injecting string or int values instead of composite data like classes, but why?). Awkward.
Third: The most important lesson I learned from Refactoring was that my code sucked. Not only did my code suck, but there was no single transformation to make it stop sucking. The best I could hope for was to make it suck less. Once I did that, I could make it suck less again. And again. Some design patterns are bad, but they exist to allow your sucky code to transition to less sucky code. So you take your globals and make them singletons. Then you eliminate your singletons. Don't get discouraged because you've just refactored to find that your code still sucks. It sucks less. So, your Configuration loading object may smell, but you might decide that it isn't the smelliest part of your code. In fact, you may find that the effort to "fix" it isn't worth it.
Yes - a method taking this many parameters should be considered a code smell. Is this method truly only doing one thing and one thing only?
If this is still true you can still lower the number of dependencies by looking at the relationships between the dependencies - are any of them closely related, could they be coupled into aggregate dependencies? E.g. you could refactor by creating a new class K that uses A, B and C internally (injected into class K by constructor, then using composition) - so the number of parameters to the method would be reduced by two.
Rinse and repeat until aggregating doesn't make sense anymore and/or you have a reasonable number of parameters.
Also see a related blog post: "Refactoring to Aggregate Services"
I'd also advise to redesign your application. In case it is not possible you can pass your IoC container as a constructor parameter. If you do not want to couple your code with a concrete implementation you can always abstract it. The code will look something like this.
public interface IAbstractContainer
{
T Resolve<T>();
}
public class ConcreteContainer: IAbstractContainer
{
private IContainer _container; // E.g. Autofac container
public ConcreteContainer(IContainer container)
{
_container = container;
{
public T Resolve<T>()
{
return _container.Resolve<T>();
}
}
public classA(IAbstractContainer container)
{
this.B = container.Resolve<ClassB>();
this.C = container.Resolve<ClassC>();
...
}
}
A ConcreteContainer instance is injected the usual way.

Patterns for using EntityFramework?

What is alternative patterns of using for Entity Framework ?
Some I know are:
"Plain" EntityFramework - aka Unity of Work
using (Data.Model c = new Data.Model())
{
var z = c.Users.Where(x=>x.Name=='John');
}
Repository pattern
//Model implements IRepository
User user = Model.Instance.Get<User>(u => u.Name == "John");
What else ?
?
A good book to look at is Martin Fowler's "Patterns of enterprise application architecture".
There he goes through some patterns for retrieving/mapping data like DTOs, Unit of work, repository pattern etc... Maybe something could be useful together with the Entity Framework. I'd have to take a look at it.
I answer your question based on the assumption that you are using Entity Framework directly in your UI/controller/Services.
It has been proven that using any ORM, inclusing EF, directly in your UI/Controllers/Services will cause a lot of problem in the future. On top of that, it makes it so hard, if not impossible, to unit test your application.
The second approach ie "Model implements repository" is also wrong in my opinion, becuase Model and Respositories have different responsiblities and based on "Single Responsibilty" part of SOLID principles you should not merge the two concepts together. Even if you want to use Active Objects pattern in your model, which I don't recommend, you must decouple your model from the ORM you use.
The best and the most recommended solution is to have an interface like IRepository or IRepository with the very basic members as the pattern suggests. something like:
Interface IRepository<T> where T:class
{
void Insert(T entity);
void Update(T entity);
void Delete(T entity);
// if you don't want to return IQueryable
T FindById(object id);
IEnumerable FindXXXXX(params)
// if you prefer to return an IQueryable
IQueryable<T> Find(Expression<Func<T, bool>> predeicate);
}
Note that some poeple beleive Repositories should not return IQueryable. Additionally, You can consider using ISpecification instead of expressions and lambda.
you would need to implement IRepositoy interface for most of your entities. Using this approach you can also mock your repositories when writing unit tests. In production, you would need to use an Ioc provider such as Unity, Ninject, Linfu, Catsle and etc. you can also benefit from microsoft's common service locator implementation to avoid coupling to a specifi IoC framework.
In the old days, I used to have a data access interface which was impleneted for a specific business domain or a service. One of the issues with this approach is that you would end up with duplicate code in different data access services if you keep track of your source code and you will eventually.
We use code similar to what you have in your unit of work example.
What we do in addition is to map objects to Data Transfer Objects.
There are many articles on the subject, but the list will be reduced substantially if you'd like a good one. This article from MSDN Magazine is pretty good, although it deals specifically with n-tier applications. But since you don't say what you're building, maybe it will help.
LINQ 2 SQL can be an alternative. Here is an article Dependency Injection with Unity and Linq to SQL DataContexts
UNITY - http://unity.codeplex.com/

Categories