I am trying to find a better way to resolve context-driven parameters using Autofac. Consider the following code :
builder.RegisterType<SqlDatabaseResourceFactory>().WithParameter("connectionStringKey", "MyConnectionStringKey").As<DatabaseResourceFactory>();
builder.RegisterType<ATypeRepository>().As<IATypeRepository>().PropertiesAutowired();
builder.RegisterType<BTypeRepository>().As<IBTypeRepository>().PropertiesAutowired();
builder.RegisterType<CTypeRepository>().As<ICTypeRepository>().PropertiesAutowired();
builder.RegisterType<DTypeRepository>().As<IDTypeRepository>().PropertiesAutowired();
In this case, each "Repository" has a property ResourceFactory, typed DatabaseResourceFactory, that has a local default (for compatibility with legacy code). This works great as long as all the types needing ResourceFactory injected use the same connection string.
If, say, C and D repositories needed a different connection string, though, this solution would no longer work. The best work-around I can think of is to use something like the following
builder.RegisterType<ATypeRepository>()
.As<IATypeRepository>()
.OnActivating(c => c.Instance.ResourceFactory = new SqlDatabaseResourceFactory("MyConnectionStringKey"));
But this now needs doing for each repository type registered, which seems overly repetitive and clunky. Is there a better solution to this type of problem. Is this problem an indication of some underlying architectural issue?
If, say, C and D repositories needed a different connection string,
If C and D need a different connection, they should get their own abstraction. For instance define a IBillingDatabaseResourceFactory and IShippingDatabaseResourceFactory. This resolves the ambiguity that's currently in your design and DI configuration.
You could use:
builder.Register(c => new CTypeRepository(new SqlDatabaseResourceFactory("C-connectionstring")).As<ICTypeRepository>().PropertiesAutowired();
Related
I am using Ninject to set up bindings for a class which is an IObservable.
I have set up a rebind to ensure that the IObservable has it's IObserver subscribed as follows...
kernel.Rebind<IAddressRepository>().To<AddressRepository>().InRequestScope()
.OnActivation(repo => repo
.Subscribe(new SyncTrackerDataEventObserver<Address, AddressRepository>()));
This seems to work OK but it really isn't ideal. SyncTrackerDataEventObserver will, when it's more than a stub have dependencies of it's own. Then we end up with this...
kernel.Rebind<IAddressRepository>().To<AddressRepository>().InRequestScope()
.OnActivation(repo => repo
.Subscribe(new SyncTrackerDataEventObserver<Address, AddressRepository>(new SyncTrackerRepository(new SyncDataSource))));
Ouch!!
What I want to do is make use of the existing bindings at this point. I'd expect to be able to write something like this (but this is just made up..)
kernel.Rebind<IAddressRepository>().To<AddressRepository>().InRequestScope()
.OnActivation(repo => repo
.Subscribe(kernel.Resolve<ISyncTrackerDataEventObserver>()));
What is the correct way to achieve this without creating a hell of hard coded dependencies and breaking IoC paradigms?
This was quite straightforward when I figured out where to look. kernel.TryGet<> will get you the service type from the current bindings.
kernel.Rebind<IAddressRepository>().To<AddressRepository>().InBackgroundJobScope()
.OnActivation(repo => repo
.Subscribe(kernel.TryGet<SyncTrackerDataEventObserver<Address, AddressRepository>>()
?? throw new ObserverBindingException("Address")));
(where ObserverBindingException is a custom exception type I created just for this purpose).
I am still new to DI and Unit Tests. I have been tasked with adding Unit Tests to some of our legacy code. I am working on a WCF web service. A lot of refactoring has had to be done. Monster classes split into separate classes that make sense. Monster methods split to multiple methods. And lastly, creating interface classes for external dependencies. This was done initially to facilitate mocking those dependencies for unit tests.
As I have gone about this the list of dependencies keeps growing and growing. I have other web services to call, SQL Servers and DB2 Databases to interact with, a config file to read, a log to write to, and reading from Sharepoint data. So far I have 10 dependencies. And every time I add one it breaks all my Unit Tests since there is a new parameter in the constructor.
If it helps, I am using .Net 4.5, Castle Windsor as my IOC, MSTest, and Moq for testing.
I have looked here How to avoid Dependency Injection constructor madness? but this doesn't provide any real solution. Only to say "your class may be doing too much." I looked into Facade and Aggregate services but that seemed to just move where things were.
So I need some help on how to make this class to "less" but still provide the same output.
public AccountServices(ISomeWebServiceProvider someWebServiceProvider,
ISomeOtherWebProvider someOtherWebProvider,
IConfigurationSettings configurationSettings,
IDB2Connect dB2Connect,
IDB2SomeOtherData dB2SomeOtherData,
IDB2DatabaseData dB2DatabaseData,
ISharepointServiceProvider sharepointServiceProvider,
ILoggingProvider loggingProvider,
IAnotherProvider AnotherProvider,
ISQLConnect SQLConnect)
{
_configurationSettings = configurationSettings;
_someWebServiceProvider = someWebServiceProvider;
_someOtherWebProvider = someOtherWebProvider;
_dB2Connect = dB2Connect;
_dB2SomeOtherData = dB2SomeOtherData;
_dB2DatabaseData = dB2DatabaseData;
_sharepointServiceProvider = sharepointServiceProvider;
_loggingProvider = loggingProvider;
_AnotherProvider = AnotherProvider;
_SQLConnect = SQLConnect;
}
Almost all of the there are in other components but I need to be able to use them in the main application and mock them in unit tests.
Here is how one of the methods is laid out.
public ExpectedResponse GetAccountData(string AccountNumber)
{
// Get Needed Config Settings
...
// Do some data validation before processing data
...
// Try to retrieve data for DB2
...
// Try to retrieve data for Sharepoint
...
// Map data to response.
...
// If error, handle it and write error to log
}
Other methods are very similar but they may be reaching out to SQL Server or one or more web services.
Ideally what I would like to have is an example of an application that needs a lot of dependencies, that has unit tests, and avoids having to keep adding a new dependency to the constructor causing you to update all your unit tests just to add the new parameter.
Thanks
Not sure if this helps, but I came up with a pattern I called GetTester that wraps the constructor and makes handling the parameters a little easier. Here's an example:
private SmartCache GetTester(out Mock<IMemoryCache> memory, out Mock<IRedisCache> redis)
{
memory = new Mock<IMemoryCache>();
redis = new Mock<IRedisCache>();
return new SmartCache(memory.Object, redis.Object);
}
Callers look like this if they need all the mocks:
SmartCache cache = GetTester(out Mock<IMemoryCache> memory, out Mock<IRedisCache> redis);
Or like this if they don't:
SmartCache cache = GetTester(out _, out _);
These still break if you have constructor changes, but you can create overloads to minimize the changes to tests. It's a hassle but easier than it would otherwise be.
So possibly your classes might be doing too much. If you're finding that you're constantly increasing the work that a class is doing and as a result are needing to provide additional objects to assist in those additional tasks then this is probably the issue and you need to consider breaking up the work.
However, if this isn't the case then another option is to have the classes take in a reference to a dependency class that provides access to either the instantiated concrete objects that implement your various interfaces or instantiated factory objects which can be used to construct objects. Then instead of constantly passing new parameters you can just pass the single object and from there pull or create objects as necessary from that.
I ran into a strange problem yesterday. I built a makeshift viewmodel locator style system yesterday using ninject as its di container. I then tried to have it resolve a moq mock implementation of a data repository interface to feed into the viewmodels through constructor injection. But, I keep getting the following exception from moq at design time.
Error 2 Unable to cast object of type 'Castle.Proxies.IADEmployeeRepoProxy_1' to type 'MVVMSupport.TestHarness.Data.IADEmployeeRepo'. D:\Users\kicksagnome\Desktop\MVVMSupport\MVVMSupport.TestHarness\App.xaml 16 13 MVVMSupport.TestHarness
Mock<IADEmployeeRepo> repo = new Mock<IADEmployeeRepo>();
repo.Setup<List<ADEmployee>>(r => r.GetAllEmployees())
.Returns(new List<ADEmployee>() { new ADEmployee() { FirstName = "Ryan Butcher" } });
Bind<IADEmployeeRepo>().ToConstant(repo.Object); //Also tried Bind<IADEmployee>().ToMethod(context => repo.Object);
It runs fine the first load of the designer and fails every time design data is changed and I rebuild the solution.
I recognize this isn't how moq is meant to be used so the question is...
1.) Is there a way to fix this issue?
2) How should I be adding design time data?
Well, you have several options.
You could have different options in your View Model depending on "IsInDesignMode", and have your design data reside there. That would be your quick and dirty option.
A better option would be to have a DataService, and a Mock one (or DesignDataService), and in your ViewModelLocator, you'll use that in your "IsInDesignMode".
From there, just add whatever you need to mock to the Interface of the DataService, this service will be injected into your view model on construction, and you can then simple have something like:
MyData = DataService.GetData();
In the real data service, you'll fetch your data, and in the design/mock one, you can fake to your liking, having your design data displayed easily.
Let me know if you have any other questions, or need more code for the example.
I just started working with Unit Testing with NMock
I one my test cases involve adding an entry in a dictionary which is then passed to the unit being tested. I define the map as:
var item = new Mock<MyClass>().Object;
var myMap = new Dictionary<MyClass, IList<MyOtherClass>>
{
{ item, completionRequirement }
};
However when I do a myMap.ContainsKey(item) inside the unit being tested it returns false.
I am able to view a proxied item in the Dictionary on inspecting it. I am guessing that I need to do something else as well on the mocked item.(Most probably define .Equals(object o)).
My question is :
How do you define the Equals(object o) for the mocked item.
Or is there a different solution to the problem altogether.
You might want to mock the dictionary as well. That is, refactor to use IDictionary<MyClass,IList<MyOtherClass>, then pass in a mocked dictionary. You can then set up expectations so that it returns mocked objects as necessary.
It's also possible that you may not need to use a mock at all in this instance. It's not possible to tell from what you've given us, but I've often found that people new to mocking can sometimes forget that you can use the real objects as well if those objects don't have cascading dependencies. For example, you don't really need to mock a class that's just a simple container. Create one and use it, instead. Just something to think about.
The approach given at http://richardashworth.blogspot.com/2011/12/using-reflection-to-create-mock-objects.html is in Java, but presents another approach to this problem using Reflection.
I like the idea of setting up a 'fake' object along the lines of what tvanfosson is suggesting.
But if you want to do it with a mocking framework, I think all you need to do is setup an expectation for what item.Object should be. In Rhino Mocks the syntax would be something like:
var knownObject = "myKey";
var mock = MockRepository.GenerateStub<IMyClass>();
mock.Stub(x=>x.Object).Return(knownObject);
That said, I have no idea what the equivalent code would be in NMocks, but it shouldn't be hard to figure it out if you're working with it (you can always ask a question on the user group).
HTH
I've read about it, I understand it's basic function--I'd like to know an example of a common, real-life use for this pattern.
For reference, I work mostly with business applications, web and windows, using the Microsoft stack.
Think of an Itinerary builder. There are lots of things you can add to you Itinerary like hotels, rental cars, airline flights and the cardinality of each is 0 to *. Alice might have a car and hotel while Bob might have two flights, no car and three hotels.
It would be very hard to create an concrete factory or even an abstract factory to spit out an Itinerary. What you need is a factory where you can have different steps, certain steps happen, others don't and generally produce very different types of objects as a result of the creation process.
In general, you should start with factory and go to builder only if you need higher grain control over the process.
Also, there is a good description, code examples and UML at Data & Object Factory.
Key use cases:
When the end result is immutable, but
doing it all with a constructor would
be too complicated
When I want to partially build
something and reuse that partially
built thing, but customize it at
the end each time
When you start with the factory pattern, but the thing being built by
the factory has too many permutations
In summary, builder keeps your constructors simple, yet permits immutability.
You said C#, but here's a trivial Java example:
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World!");
System.out.println(sb.toString());
As opposed to:
String msg = "";
msg += "Hello";
msg += " ";
msg += "World!";
System.out.println(msg);
EDIT: You will see in my comments that I may have rushed into answering this question, and confused myself in the process. I will go ahead and edit this to work with the Abstract Factory, as I think I originally intended, but please note that this is mainly for reference, not necessarily as a response to the original question.
The most common example I've seen described deals with how GUI components are built.
For example, if you were designing a form for your application, whose GUI components could take on multiple representations (perhaps based on which platform you were running on), you would design an abstract factory to handle the creation of those components.
In order to add new controls to the form, the code might look something like this:
public MyForm ()
{
GuiFactory factory = new Win32Factory ();
Button btn = factory.CreateButton ();
btn.Text = "Go!"
btn.Location = new Point (15, 50);
this.Controls.Add (btn);
}
This satisfies the Abstract Factory pattern because you can create different instances of the factory object to create different representations of your created objects without changing the client code (this is a rudimentary example, but I think normally you wouldn't create the Win32Factory using new, it would be acquired via some other abstraction).
A common example that we used to see all the time was a "sysgen" of an operating system. you had a process that selected all the modules you needed, configured them, and returned a bootable image that had been customized.
One use case that I've encountered is when having multiple data sources. The particular case involved a cache and a database. The majority of the data was pulled from cache, or not. The second loader looked at the data to see whether or not it was loaded from the cache. It would query the database to finish populating the data.
Sometimes it can be helpful to think of non-software related example of design patterns in order to understand them.
I have a system I am working on now that uses a builder to create an order. The order is a class composed of several other classes. My builder creates and validates the associated classes, and if all are valid it then creates an instance of the order class. This way I can be sure that I never have an instance of an order that is missing data.