How simplify creating repositories in class UnitOfWork? - c#

Ignore the fact that DbContext in Entity Framework is unit of work right now.
I wonder how I can simplify creating repositories in class UnitOfWork because now I must add property to that class each time when I create new repository class? I don't want generic repository class.
public class UnitOfWork
{
private SchoolContext _context = new SchoolContext();
private IDepartmentRepository _departmentRepository;
private ICourseRepository _courseRepository;
public IDepartmentRepository DepartmentRepository
{
get
{
if (this._departmentRepository == null)
{
this._departmentRepository = new DepartmentRepository(_context);
}
return _departmentRepository;
}
}
public ICourseRepository CourseRepository
{
get
{
if (this._courseRepository == null)
{
this._courseRepository = new CourseRepository(_context);
}
return _courseRepository;
}
}
public void Save()
{
_context.SaveChanges();
}
}

It's your architecture, so you're the one responsible for providing properties for your repository types. There're several ways of simplifying your code:
There's a shorter way of writing your properties:
ICourseRepository _courseRepository;
public ICourseRepository CourseRepository =>
_courseRepository ?? (_courseRepository = new CourseRepository(_context));
It'll be a little longer with C# 5 or lower (you'll need explicit get accessor). You can also use Lazy<T> type.
Dependency injection. Your getter will look like this:
_someDI.Get<ICourseRepository>(new Parameter(_context));
You'll need to register your types first like this:
_someDI.Register<ICourseRepository, CourseRepository>();
or all types together:
_someDI.RegisterAllImplementingInterface<IBaseRepository>().AsImplementingInterfaces();
It'll also make using single method possible, though types will be less discoverable:
TRep GetRepository<TRep>() where TRep : IBaseRepository =>
_someDI.Get<TRep>(new Parameter(_context));
Code generation using T4. You can read project files to get the list of types and then generate the properties based on that information.
(Maybe) Code generation built into C# 7 when it becomes available. Whether it'll be available and what exactly will be incuded is still TBD.

Related

Creating a Moq of a static extension method from LLBLGen

i'm trying to use Moq to mock an extension method from the IDataAccessAdapter interface from LLBLGen. Here is FetchQueryAsync the extension method.
Doing so gave me the error that i can't Mock static extension methods. However there is no way i can change the code. So i tried creating a wrapper class, yet i had no success doing that either because i do not know how to apply it.
In the method Fetch, i want FetchQueryAsync to return an object i specified during the test and not actually execute the query.
public class QueryHandler
{
private IDataAccessAdapterProvider dataAccessAdapterProvider;
public QueryHandler(IDataAccessAdapterProvider provider)
{
this.dataAccessAdapterProvider = provider;
}
private async Task<T> Fetch(DynamicQuery<T> query)
{
using (IDataAccessAdapter adapter = dataAccessAdapterProvider.Provide()
{
result = await adapter.FetchQueryAsync(query)
}
}
}
public class DataAccessAdapterProvider : IDataAccessAdapterProvider
{
public IDataAccessAdapter Provide()
{
var adapter = new DataAccessAdapter();
return adapter;
}
}
So in my Unit Test i have this:
List<int> il = new List<int>();
Mock<IDataAccessAdapterProvider> mock = new Mock<IDataAccessAdapterProvider>();
mock.Setup(m => m.Provide()
.FetchQueryAsync<int>(It.IsAny<DynamicQuery<int>>()))
.ReturnsAsync(il);
This won't work however because it's not supported.
So i tried wrapping the method as such.
interface IWrap
{
Task<List<TElement>> FetchQueryAsync<TElement>(IDataAccessAdapter adapter, DynamicQuery<TElement> query);
}
public class Wrap : IWrap
{
public async Task<List<TElement>> FetchQueryAsync<TElement>(IDataAccessAdapter adapter, DynamicQuery<TElement> query)
{
return await adapter.FetchQueryAsync(query);
}
}
How do i apply this wrapper with Moq to mock the interface?
You started with an extension method and then you created your IWrap interface along with an implementation that uses the extension method. That's perfect.
Now all you need is to inject it into your class, just like IDataAccessAdapterProvider is already injected:
public class QueryHandler
{
private readonly IDataAccessAdapterProvider _dataAccessAdapterProvider;
private readonly IWrap _wrap; //I'm assuming you'll want a different name.
public QueryHandler(IDataAccessAdapterProvider provider, IWrap wrap)
{
_dataAccessAdapterProvider = provider;
_wrap = wrap;
}
(I applied a common convention there. Prefixing the field names with an underscore - _wrap - means that the field and constructor arguments have different names, so you don't need to specify this.wrap. Plus when people see that underscore elsewhere they'll know it's a field.)
Now you can mock the interface:
var mock = new Mock<IWrap>();
var returnedFromMock = new List<int> { 1, 2, 3 };
mock.Setup(x => x.FetchQueryAsync<int>(It.IsAny<IDataAccessAdapter>(), It.IsAny<DynamicQuery<int>>()))
.ReturnsAsync(returnedFromMock);
You mentioned that there is no way you can change the code. I'm not sure which part you can't change, but if you can't change QueryHandler to replace its concrete dependencies then this may just be a cautionary tale about static dependencies.
You have the source code, though. If you can't change the existing class, perhaps you can just create a new one from the existing source code. If someone asks why you duplicated an existing class, just say (tactfully) that you don't want to duplicate code - you'd rather fix the existing one so that it's testable.

C# MongoDB: How to correctly map a domain object?

I recently started reading Evans' Domain-Driven design book and started a small sample project to get some experience in DDD. At the same time I wanted to learn more about MongoDB and started to replace my SQL EF4 repositories with MongoDB and the latest official C# driver.
Now this question is about MongoDB mapping. I see that it is pretty easy to map simple objects with public getters and setters - no pain there. But I have difficulties mapping domain entities without public setters. As I learnt, the only really clean approach to construct a valid entity is to pass the required parameters into the constructor. Consider the following example:
public class Transport : IEntity<Transport>
{
private readonly TransportID transportID;
private readonly PersonCapacity personCapacity;
public Transport(TransportID transportID,PersonCapacity personCapacity)
{
Validate.NotNull(personCapacity, "personCapacity is required");
Validate.NotNull(transportID, "transportID is required");
this.transportID = transportID;
this.personCapacity = personCapacity;
}
public virtual PersonCapacity PersonCapacity
{
get { return personCapacity; }
}
public virtual TransportID TransportID
{
get { return transportID; }
}
}
public class TransportID:IValueObject<TransportID>
{
private readonly string number;
#region Constr
public TransportID(string number)
{
Validate.NotNull(number);
this.number = number;
}
#endregion
public string IdString
{
get { return number; }
}
}
public class PersonCapacity:IValueObject<PersonCapacity>
{
private readonly int numberOfSeats;
#region Constr
public PersonCapacity(int numberOfSeats)
{
Validate.NotNull(numberOfSeats);
this.numberOfSeats = numberOfSeats;
}
#endregion
public int NumberOfSeats
{
get { return numberOfSeats; }
}
}
Obviously automapping does not work here. Now I can map those three classes by hand via BsonClassMaps and they will be stored just fine. The problem is, when I want to load them from the DB I have to load them as BsonDocuments, and parse them into my domain object. I tried lots of things but ultimately failed to get a clean solution. Do I really have to produce DTOs with public getters/setters for MongoDB and map those over to my domain objects? Maybe someone can give me some advice on this.
It is possible to serialize/deserialize classes where the properties are read-only. If you are trying to keep your domain objects persistance ignorant, you won't want to use BsonAttributes to guide the serialization, and as you pointed out AutoMapping requires read/write properties, so you would have to register the class maps yourself. For example, the class:
public class C {
private ObjectId id;
private int x;
public C(ObjectId id, int x) {
this.id = id;
this.x = x;
}
public ObjectId Id { get { return id; } }
public int X { get { return x; } }
}
Can be mapped using the following initialization code:
BsonClassMap.RegisterClassMap<C>(cm => {
cm.MapIdField("id");
cm.MapField("x");
});
Note that the private fields cannot be readonly. Note also that deserialization bypasses your constructor and directly initializes the private fields (.NET serialization works this way also).
Here's a full sample program that tests this:
http://www.pastie.org/1822994
I'd go with parsing the BSON documents and move the parsing logic to a factory.
First define a factory base class, which contains a builder class. The builder class will act as the DTO, but with additional validation of the values before constructing the domain object.
public class TransportFactory<TSource>
{
public Transport Create(TSource source)
{
return Create(source, new TransportBuilder());
}
protected abstract Transport Create(TSource source, TransportBuilder builder);
protected class TransportBuilder
{
private TransportId transportId;
private PersonCapacity personCapacity;
internal TransportBuilder()
{
}
public TransportBuilder WithTransportId(TransportId value)
{
this.transportId = value;
return this;
}
public TransportBuilder WithPersonCapacity(PersonCapacity value)
{
this.personCapacity = value;
return this;
}
public Transport Build()
{
// TODO: Validate the builder's fields before constructing.
return new Transport(this.transportId, this.personCapacity);
}
}
}
Now, create a factory subclass in your repository. This factory will construct domain objects from the BSON documents.
public class TransportRepository
{
public Transport GetMostPopularTransport()
{
// Query MongoDB for the BSON document.
BsonDocument transportDocument = mongo.Query(...);
return TransportFactory.Instance.Create(transportDocument);
}
private class TransportFactory : TransportFactory<BsonDocument>
{
public static readonly TransportFactory Instance = new TransportFactory();
protected override Transport Create(BsonDocument source, TransportBuilder builder)
{
return builder
.WithTransportId(new TransportId(source.GetString("transportId")))
.WithPersonCapacity(new PersonCapacity(source.GetInt("personCapacity")))
.Build();
}
}
}
The advantages of this approach:
The builder is responsible for building the domain object. This allows you to move some trivial validation out of the domain object, especially if the domain object doesn't expose any public constructors.
The factory is responsible for parsing the source data.
The domain object can focus on business rules. It's not bothered with parsing or trivial validation.
The abstract factory class defines a generic contract, which can be implemented for each type of source data you need. For example, if you need to interface with a web service that returns XML, you just create a new factory subclass:
public class TransportWebServiceWrapper
{
private class TransportFactory : TransportFactory<XDocument>
{
protected override Transport Create(XDocument source, TransportBuilder builder)
{
// Construct domain object from XML.
}
}
}
The parsing logic of the source data is close to where the data originates, i.e. the parsing of BSON documents is in the repository, the parsing of XML is in the web service wrapper. This keeps related logic grouped together.
Some disadvantages:
I haven't tried this approach in large and complex projects yet, only in small-scale projects. There may be some difficulties in some scenarios I haven't encountered yet.
It's quite some code for something seemingly simple. Especially the builders can grow quite large. You can reduce the amount of code in the builders by converting all the WithXxx() methods to simple properties.
A better approach to handling this now is using MapCreator (which was possibly added after most of these answers were written).
e.g. I have a class called Time with three readonly properties: Hour, Minute and Second. Here's how I get it to store those three values in the database and to construct new Time objects during deserialization.
BsonClassMap.RegisterClassMap<Time>(cm =>
{
cm.AutoMap();
cm.MapCreator(p => new Time(p.Hour, p.Minute, p.Second));
cm.MapProperty(p => p.Hour);
cm.MapProperty(p => p.Minute);
cm.MapProperty(p => p.Second);
}
Niels has an interesting solution but I propose a much different approach:
Simplify your data model.
I say this because you are trying to convert RDBMS style entities to MongoDB and it doesnt map over very well, as you have found.
One of the most important things to think about when using any NoSQL solution is your data model. You need to free your mind of much of what you know about SQL and relationships and think more about embedded documents.
And remember, MongoDB is not the right answer for every problem so try not to force it to be. The examples you are following may work great with standard SQL servers but dont kill yourself trying to figure out how to make them work with MongoDB - they probably dont. Instead, I think a good excercise would be trying to figure out the correct way to model the example data with MongoDB.
Consider NoRM, an open-source ORM for MongoDB in C#.
Here are some links:
http://www.codevoyeur.com/Articles/20/A-NoRM-MongoDB-Repository-Base-Class.aspx
http://lukencode.com/2010/07/09/getting-started-with-mongodb-and-norm/
https://github.com/atheken/NoRM (download)

How to make a Generic Repository?

I am wondering if anyone has any good tutorials(or maybe even a library that is already made and well documented) on making a generic repository.
I am using currently linq to sql but it might change so I don't know if you can make a generic repository that would take little to no changes if I would say switch to entity framework.
Thanks
I think I should also add why I want a generic repository. The reason is in my database I have like corporate tables(users who's subscriptions are paid by someone else) and individual tables(people who find my site through google or whatever and pay for their own subscription)
But I will have 2 very similar tables. For instance I have 2 settings tables one for corporate users and one for the individuals.
Now since they are 2 different tables I need 2 different insert methods as I am inserting it into 2 different tables and at this current time only one field is different(that is the PK).
So now I need all these duplicate methods and I don't want that. Maybe what I have in my database is could be considered as a design flaw(and maybe it is) but one of the reasons behind this was if needed I can break up my database into 2 different databases very easy and I am not going to change my design anytime soon.
Here is my answer to another question of the same type. Hope it helps:
Advantage of creating a generic repository vs. specific repository for each object?
Edit:
It sounds like you want to treat two concrete types as one logical type. To do that, first define the logical type:
public interface ISubscription
{
// ...
}
Then, define the concrete types as part of your data model (interfaces would be implemented in another partial class):
[Table("CorporateSubscription")]
public partial class CorporateSubscription : ISubscription
{
}
[Table("IndividualSubscription")]
public partial class IndividualSubscription : ISubscription
{
}
Next, define the repository which operates on the logical type:
public interface ISubscriptionRepository
{
CorporateSubscription GetCorporate(string key);
IndividualSubscription GetIndividual(int userId);
IEnumerable<ISubscription> ListAll();
IEnumerable<CorporateSubscription> ListCorporate();
IEnumerable<IndividualSubscription> ListIndividual();
void Insert(ISubscription subscription);
}
Finally, implement the interface by using both tables:
public class SubscriptionRepository : ISubscriptionRepository
{
private readonly YourDataContext _dataContext;
public SubscriptionRepository(YourDataContext dataContext)
{
_dataContext = dataContext;
}
#region ISubscriptionRepository
public CorporateSubscription GetCorporate(string key)
{
return _dataContext.CorporateSubscriptions.Where(c => c.Key == key).FirstOrDefault();
}
public IndividualSubscription GetIndividual(int userId)
{
return _dataContext.IndividualSubscriptions.Where(i => i.UserId == userId).FirstOrDefault();
}
public IEnumerable<ISubscription> ListAll()
{
return ListCorporate()
.Cast<ISubscription>()
.Concat(ListIndividual().Cast<ISubscription>());
}
public IEnumerable<CorporateSubscription> ListCorporate()
{
return _dataContext.CorporateSubscriptions;
}
public IEnumerable<IndividualSubscription> ListIndividual()
{
return _dataContext.IndividualSubscriptions;
}
public void Insert(ISubscription subscription)
{
if(subscription is CorporateSubscription)
{
_dataContext.CorporateSubscriptions.InsertOnCommit((CorporateSubscription) subscription);
}
else if(subscription is IndividualSubscription)
{
_dataContext.IndividualSubscriptions.InsertOnCommit((IndividualSubscription) subscription);
}
else
{
// Forgive me, Liskov
throw new ArgumentException(
"Only corporate and individual subscriptions are supported",
"subscription");
}
}
#endregion
}
Here is an example of an insert. Don't get too wrapped up in the presenter class; I just needed a situation in which subscriptions would be created based on a flag:
public class CreateSubscriptionPresenter
{
private readonly ICreateSubscriptionView _view;
private readonly ISubscriptionRepository _subscriptions;
public CreateSubscriptionPresenter(
ICreateSubscriptionView view,
ISubscriptionRepository subscriptions)
{
_view = view;
_subscriptions = subscriptions;
}
public void Submit()
{
ISubscription subscription;
if(_view.IsCorporate)
{
subscription = new CorporateSubscription();
}
else
{
subscription = new IndividualSubscription();
}
subscription.Notes = _view.Notes;
_subscriptions.Insert(subscription);
}
}
Great Linq to Sql resources:
A t4 template that by generates exactly what is created by default, but can be fully customised.
http://l2st4.codeplex.com/
Using Linq to Sql for a multi tier application. It has a GenericObjectDataSource which I have found very handy
http://multitierlinqtosql.codeplex.com
Search all properties of an IQueryable with one single search
http://naspinski.codeplex.com/

IoC and constructor over-injection anti-pattern resolution

This question is a result of a post by Jeffery Palermo on how to get around branched code and dependency injection http://jeffreypalermo.com/blog/constructor-over-injection-anti-pattern/
In his post, Jeffery has a class (public class OrderProcessor : IOrderProcessor) that takes 2 interfaces on the constructor. One is a validator IOrderValidator and an IOrderShipper interface. His method code branches after only using methods on the IOrderValidator interface and never uses anything on the IOrderShipper interface.
He suggests creating a factory that will call a static method to get the delegate of the interface. He is creating a new object in his refactored code which seems unnecessary.
I guess the crux of the issue is we are using IoC to build all our objects regardless if they're being used or not. If you instantiate an object with 2 interfaces and have code that could branch to not use one of them, how do you handle it?
In this example, we assume _validator.Validate(order) always returns false and the IOrderShipper.Ship() method is never called.
Original Code:
public class OrderProcessor : IOrderProcessor
{
private readonly IOrderValidator _validator;
private readonly IOrderShipper _shipper;
public OrderProcessor(IOrderValidator validator, IOrderShipper shipper)
{
_validator = validator;
_shipper = shipper;
}
public SuccessResult Process(Order order)
{
bool isValid = _validator.Validate(order);
if (isValid)
{
_shipper.Ship(order);
}
return CreateStatus(isValid);
}
private SuccessResult CreateStatus(bool isValid)
{
return isValid ? SuccessResult.Success : SuccessResult.Failed;
}
}
public class OrderShipper : IOrderShipper
{
public OrderShipper()
{
Thread.Sleep(TimeSpan.FromMilliseconds(777));
}
public void Ship(Order order)
{
//ship the order
}
}
Refactored Code
public class OrderProcessor : IOrderProcessor
{
private readonly IOrderValidator _validator;
public OrderProcessor(IOrderValidator validator)
{
_validator = validator;
}
public SuccessResult Process(Order order)
{
bool isValid = _validator.Validate(order);
if (isValid)
{
IOrderShipper shipper = new OrderShipperFactory().GetDefault();
shipper.Ship(order);
}
return CreateStatus(isValid);
}
private SuccessResult CreateStatus(bool isValid)
{
return isValid ? SuccessResult.Success : SuccessResult.Failed;
}
}
public class OrderShipperFactory
{
public static Func<IOrderShipper> CreationClosure;
public IOrderShipper GetDefault()
{
return CreationClosure(); //executes closure
}
}
And here is the method that configures this factory at start-up time (global.asax for ASP.NET):
private static void ConfigureFactories()
{
OrderShipperFactory.CreationClosure =
() => ObjectFactory.GetInstance<IOrderShipper>();
}
I just posted a rebuttal of Jeffrey Palermos post.
In short, we should not let concrete implementation details influence our design. That would be violating the Liskov Substitution Principle on the architectural scale.
A more elegant solution lets us keep the design by introducing a Lazy-loading OrderShipper.
I'm running late for a meeting, but a few quick points...
Sticking to the code branching of using only one dependency, there are two branches to propose:
Applying DDD practices, you would not have an OrderProcessor with a dependency on IOrderValidator. Instead, you'd make the Order() entity be responsible for its own validation. Or, stick to your IOrderValidator, but have its dependency within the OrderShipper() that is implemented - since it will return any error codes.
Ensure the dependencies being injected are constructed using a Singleton approach (and configured as Singleton in the IoC container being used). This resolves any memory concerns.
Like someone else that mentioned here, the point is to break the dependency on concrete classes and loosely couple the dependencies using Dependency Injection with some IoC container in use.
This makes future refactoring and swapping out legacy code far easier on a grand scale by limiting the technical debt incurred in the future. Once you have a project near 500,000 lines of code, with 3000 unit tests, you'll know first hand why IoC is so important.

Dynamically extending a type at runtime?

I have the need to extend instances of various types at runtime. Most of the time, I need to work with instances of the original type, however in a few circumstances, I need to create kind of an extension-wrapper around those types that add a couple pieces of contextual information. Something along the lines of the following (which is not actually valid .NET/C# code...but it illustrates the point):
public abstract class BaseClass
{
// ...
}
public class Concrete1: BaseClass
{
// ...
}
public class Concrete2: BaseClass
{
// ...
}
public class WrapperExtender<T>: T // Extending from T here is actually invalid!
where T: BaseClass
{
public WrapperExtender(T extensionTarget)
{
m_extensionTarget = extensionTarget;
}
private readonly T m_extensionTarget;
public object ContextualReference { get; }
public int ContextualValue { get; }
// DERP: Would need to implement overrides of T here...buuut...can't...
}
// In use, special case:
var instance = new Concrete1();
var extendedInstance = new WrapperExtender(instance);
var processor = new SomeProcessorRequiringExtendedInstance();
processor.DoProcessing(extendedInstance);
Another example of this would probably be Microsoft Entity Framework v4.0, or nHibernate. Both of these frameworks provide dynamically extended instances of your entity types, wrapping them internally to provide, at runtime, the hooks required to keep a data/object/session context up to date with changes made to your entity instances. My needs are not nearly as complex, and the generics scenario above would work beautifully, if only there was a way to blend generics and dynamic typing somehow.
Anyway, I'm hoping someone knows how to achieve the above scenario. Or, perhaps even better, someone knows a better solution. I don't care much for the idea of dynamically extending a type like that at runtime (it doesn't make as much sense as it does in the EF/nHibernate scenario.) At the moment, its the only thing I can really think of that will provide me with the information I need in the processor for each type passed in to DoProcessing.
The problems that EF etc are solving is different, and relates to tihngs like lazy loading, etc. I'm simply not sure that the level of complexity that dynamic subclassing requires is worth it for this scenario. A few thoughts, though:
have a property bag in your object for flexible additional properties; if necessary the property-bag can be exposed to data-binding APIs via ICustomTypeDescriptor
simply wrap your object in an implementation-specific tuple that contains the existing object and the additional properties (no subclassing)
It is a shame that C# doesn't support "mixins", which would also be a nice way of implementing this type of thing with interfaces.
I know that this can be accomplished using dynamicproxy (which is what NHibernate uses to accomplish this task) which you can find out more about here:
DynamicProxy Page
DynamicProxy tutorial
If all you need is some additional properties, why not just create a context property in BaseClass?
something like this, where ContextBag is either a generic collection class or specially defined context collection:
Public ContextBag Context
{
get;
set;
}
When setting/accessing the context, you will be using syntax like this:
SubClass.Context.GetInt(ContextDefinition, ContextName);
SubClass.Context.Add(ContextDefinition, ContextName, ContextValue);
Found a better solution than temporarily extending. I created an actual context object that contained the state I needed available. Whenever that context exists, I initialize the context and set a static property that can be used to retrieve the context object from anywhere, alleviating the need to update all the dependencies of my larger process to take the context in as a parameter (which isn't always possible, as sometimes the calls are made in other contexts.)
public class SomeContext
{
public SomeContext(object stateData1, object stateData2)
{
StateData1 = stateData1;
StateData2 = stateData2;
}
public virtual object StateData1 { get; private set; }
public virtual object StateData2 { get; private set; }
[ThreadStatic]
private static SomeContext m_threadInstance;
public static SomeContext Current
{
get
{
return m_threadInstance;
}
set
{
if (value != null && m_threadInstance != null)
throw new InvalidOperationException("This context has already been initialized for the current thread.");
m_threadInstance = value;
}
}
}
public class SomeContextScope: IDisposable
{
public SomeContextScope(object stateData1, object stateData2)
{
if (SomeContext.Current == null)
{
SomeContext context = new SomeContext(stateData1, stateData2);
SomeContext.Current = context;
m_contextCreated = true;
}
}
private bool m_contextCreated;
public void Dispose()
{
if (m_contextCreated)
{
SomeContext.Current = null;
}
}
}
public class ComplexProcessor
{
public ComplexProcessor(...) // Lots of dependencies injected
public void DoProcessing(BaseClass instance)
{
// do some work with instance
if (SomeContext.Current != null)
{
// do contextually sensitive stuff for SomeContext with instance
// call a dependency that does contextually sensitive stuff
}
// do some more work with instance
// call a dependency that does contextually sensitive stuff
if (SomeOtherContext.Current != null)
{
// do contextually sensitive stuff for SomeOtherContext with instance
// call a dependency that does contextually sensitive stuff
}
// call a dependency that does contextually sensitive stuff
}
}
// The original setup of the context and initiation of processing
public void SomeOperation(...)
{
using (SomeContextScope scope = new SomeContextScope(stateData1, stateData2))
{
// ... do some work
var processor = complexProcessorFactory.CreateInstance();
processor.DoProcesing(data);
// ... do more work
}
}
I like the way this works. Context is the state within which behavior executes. It has always felt clunky to me to have to pass contextual data around with other objects, and have dozens of methods or method overloads that take in and pass along various forms of contextual data. By setting up a context object that is globally available for the duration of that context, my code is a lot cleaner, and my dependencies are more concise. It should be mockable too, since the Current property is read/write, I can create a mock context in a BDD specification or TDD unit test whenever one is required without a lot of hassle.

Categories