Can Ninject be instructed to apply context-based logic to all bindings? - ninject

We've begun using Dependency Injection recently, and we've chosen Ninject 2 (for now) as our IoC Container. As I refactor our solution to incorporate DI principles, I've run into something that bugs me a little, and I'm wondering if there's an easy way to get around it.
For our data layer, we have a whole bunch of data-access classes that inherit the same generic class (EntityMapper). While in the past we've always constructed a new instance of these classes when we needed one, they really could all be changed into Singletons. We've overridden ObjectDataSource to use Ninject to instantiate its data-access object, so any time we create an ObjectDataSource that points to one of our EntityMapper classes, Ninject will use its default self-binding strategy to inject the necessary dependencies. Since there are so many of these classes, we'd rather not have to create an explicit binding for each of our EntityMapper classes, and we'd rather not have to put a special attribute on every one of them either. However, I would like to be able to instruct Ninject to make any instance of EntityMapper into a singleton class. Something like this:
Bind(t => typeof(IEntityMapper).IsAssignableFrom(t)).InSingletonScope();
Is there any way to do this?

You can use the conventions extension to do the following
var kernel = new StandardKernel();
kernel.Scan( x=>
{
x.FromAssemblyContaining<MyEntityMapper>();
x.FromCallingAssembly();
x.WhereTypeInheritsFrom<IEntityMapper>();
x.InSingletonScope();
} );

Related

Dependency injection on child object

I'm trying to find how I can use dependency injection to inject a ConnectionString or a custom AppSetting object so far i end up in the startup using
services.Configure<IConnectionStrings>(Configuration.GetSection("MyConnection"));
example layer
Web MVC application
Business Logic (class library)
Repository (class library)
DAL (class library)
Model (class library)
where web see only Business logic and so on, on model is available for all.
In the DAL project I have an object that takes care of connecting and running queries against my database (CDbTools object).
Now, how can I inject directly into CDbTools without going from controller down to DAL.
Thank you.
Dependency injection definitely takes a little getting used to, and you won't be creating objects quite the way you're used to. What you want to do is first is modify your CDbTools to take the injected strings.
public CDbTools(IConnectionStrings strings)
{
_connectionString = strings
}
The next step will be to actually inject the CDbTools into the classes that need it as well. First, register it in the startup.
services.AddScoped<CDbTools>();
You'll need to follow this up the chain. Don't think of it as passing the objects from the top level down - that will mess up your separation of concerns. Each layer has the lower layer injected in. This won't just get you the injection of your string you are looking for. It will let you mock things easier, swap layers easier, and a slew of other benefits.
I believe you should add this to your ConfigureServices method:
services.Configure<CustomSettings>(settings =>
{
Configuration.GetSection("CustomSettings").Bind(settings);
});
Where services is your IServiceCollection object and CustomSettings is your custom configuration class that you want to inject. That custom object should map to your settings fields.
Hope this helps!

Network storage design pattern

Let's say I have a few controllers. Each controller can at some point create new objects which will need to be stored on the server. For example I can have a RecipeCreationViewController which manages a form. When this form is submitted, a new Recipe object is created and needs to be saved on the server.
What's the best way to design the classes to minimize complexity and coupling while keeping the code as clean and readable as possible?
Singleton
Normally I would create a singleton NetworkAdapter that each controller can access directly in order to save objects.
Example:
[[[NetworkAdapter] sharedAdapter] saveObject:myRecipe];
But I've realized that having classes call singletons on their own makes for coupled code which is hard to debug since the access to the singleton is hidden in the implementation and not obvious from the interface.
Direct Reference
The alternative is to have each controller hold a reference to the NetworkAdapter and have this be passed in by the class that creates the controller.
For example:
[self.networkAdapter saveObject:myRecipe];
Delegation
The other approach that came to mind is delegation. The NetworkAdapter can implement a "RemoteStorageDelegate" protocol and each controller can have a remoteStorageDelegate which it can call methods like saveObject: on. The advantage being that the controllers don't know about the details of a NetworkAdapter, only that the object that implements the protocol knows how to save objects.
For example:
[self.remoteStorageDelegate saveObject:myRecipe];
Direct in Model
Yet another approach would be to have the model handle saving to the network directly. I'm not sure if this is a good idea though.
For example:
[myRecipe save];
What do you think of these? Are there any other patterns that make more sense for this?
I would also stick with Dependency Injection in your case. If you want to read about that you will easily find good articles in the web, e.g. on Wikipedia. There are also links to DI frameworks in Objective C.
Basically, you can use DI if you have two or more components, which must interact but shouldn't know each other directly in code. I'll elaborate your example a bit, but in C#/Java style because I don't know Objective C syntax. Let's say you have
class NetworkAdapter implements NetworkAdapterInterface {
void save(object o) { ... }
}
with the interface
interface NetworkAdapterInterface {
void save(object o);
}
Now you want to call that adapter in a controller like
class Controller {
NetworkAdapterInterface networkAdapter;
Controller() {
}
void setAdapter(NetworkAdapterInterface adapter) {
this.networkAdapter = adapter;
}
void work() {
this.networkAdapter.save(new object());
}
}
Calling the Setter is where now the magic of DI can happen (called Setter Injection; there is also e.g. Constructor Injection). That means that you haven't a single code line where you call the Setter yourself, but let it do the DI framework. Very loose coupled!
Now how does it work? Typically with a common DI framework you can define the actual mappings between components in a central code place or in a XML file. Image you have
<DI>
<component="NetworkAdapterInterface" class="NetworkAdapter" lifecycle="singleton" />
</DI>
This could tell the DI framework to automatically inject a NetworkAdapter in every Setter for NetworkAdapterInterface it finds in your code. In order to do this, it will create the proper object for you first. If it builds a new object for every injection, or only one object for all injections (Singleton), or e.g. one object per Unit of Work (if you use such a pattern), can be configured for each type.
As a sidenote: If you are unit testing your code, you can also use the DI framework to define completely other bindings, suitable for your test szenario. Easy way to inject some mocks!

Composition of Objects

I have a class that acts as a manager and does some work.
A servlet that starts up when the application server starts up instantiates this manager.
I need to add another class that will do other work, and needs to coordinate with the manager.
I was thinking about adding the class to the manager as an instance variable.
Should I have the manager instantiate the new class (like in the constructor), or have the servlet instantiate the new class and call manager.setNewClass() after the manager has been instantiated?
Well, as a gross-over-generalization, you should instantiate it in the servlet and pass it into the manager (either via a constructor parameter, or via setNewClass())... Inject the dependencies rather than hard-code them.
However, depending on your exact use-case, even that might not be the right answer. You might be better off with a Builder for constructing the manager class. That way, the builder manages the construction of the entire manager (including any dependencies) rather than hard-coding it into the servlet. This would move the dependency out of the servlet and into the builder (which you can better deal with in tests and other code).
The short answer is that there's no silver bullet. Without knowing the hard relationships between all of the classes, and the roles and responsibilities, it's hard to say the best method. But instantiating in a constructor is almost never a good idea and you should inject the dependency in some form or another (but from where is up for debate)...
This reminds me of the FFF pattern.
It does not matter where you create the instance. Just create wherever it fits you best, and if you need it somewhere else, just apply some basic refactoring.
If you really need decoupling try using some tool like Guice, but only if you really need it.
You should do the latter -- it decouples the manager from its delegate. To do the decoupling correctly, you should create an interface that defines the behavior the manager expects, and then provide an implementation via inversion of control/dependency injection. This will allow you to test the manager and its worker class (I called it a delegate, but it might not be) in isolation.
EDIT -- this answer assumes java because you mentioned servlet.
You have your manager class, in it you expect an interface
class Manager {
Worker worker;
Manager(Worker worker) {
this.worker = workder
}
}
Worker is an interface. It defines behavour but not implementation
interface Worker {
public void doesSomething(); //method definition but no implementation
}
you now need to create an implementation
class WorkerImpl implements Worker {
// must define a doesSomething() implementation
}
The manager just knows it gets some Worker. You can provide any class that implements the interface. This is decoupling -- the Manager is not bound to any particular implementation, it is bound only to the behavour of a worker.

Alternatives for the singleton pattern?

I have been a web developer for some time now using ASP.NET and C#, I want to try and increase my skills by using best practices.
I have a website. I want to load the settings once off, and just reference it where ever I need it. So I did some research and 50% of the developers seem to be using the singleton pattern to do this. And the other 50% of the developers are ant-singleton. They all hate singletons. They recommend dependency injection.
Why are singletons bad? What is best practice to load websites settings? Should they be loaded only once and referenced where needed? How would I go about doing this with dependency injection (I am new at this)? Are there any samples that someone could recommend for my scenario? And I also would like to see some unit test code for this (for my scenario).
Thanks
Brendan
Generally, I avoid singletons because they make it harder to unit test your application. Singletons are hard to mock up for unit tests precisely because of their nature -- you always get the same one, not one you can configure easily for a unit test. Configuration data -- strongly-typed configuration data, anyway -- is one exception I make, though. Typically configuration data is relatively static anyway and the alternative involves writing a fair amount of code to avoid the static classes the framework provides to access the web.config anyway.
There are a couple of different ways to use it that will still allow you to unit test you application. One way (maybe both ways, if your singleton doesn't lazily read the app.cofnig) is to have a default app.config file in your unit test project providing the defaults required for your tests. You can use reflection to replace any specific values as needed in your unit tests. Typically, I'd configure a private method that allows the private singleton instance to be deleted in test set up if I do make changes for particular tests.
Another way is to not actually use the singleton directly, but create an interface for it that the singleton class implements. You can use hand injection of the interface, defaulting to the singleton instance if the supplied value is null. This allows you to create a mock instance that you can pass to the class under test for your tests, but in your real code use the singleton instance. Essentially, every class that needs it maintains a private reference to the singleton instance and uses it. I like this way a little better, but since the singleton will be created you may still need the default app.config file, unless all of the values are lazily loaded.
public class Foo
{
private IAppConfiguration Configuration { get; set; }
public Foo() : this(null) { }
public Foo( IAppConfiguration config )
{
this.Configuration = config ?? AppConfiguration.Instance;
}
public void Bar()
{
var value = this.Config.SomeMaximum;
...
}
}
There's a good discussion of singleton patterns, and coding examples here... http://en.wikipedia.org/wiki/Singleton_pattern See also here... http://en.wikipedia.org/wiki/Dependency_injection
For some reason, singletons seem to divide programmers into strong pro- and anti- camps. Whatever the merits of the approach, if your colleagues are against it, it's probably best not to use one. If you're on your own, try it and see.
Design Patterns can be amazing things. Unfortunately, the singleton seems to stick out like a sore thumb and in many cases can be considered an anti-pattern (it promotes bad practices). Bizarely, the majority of developers will only know one design pattern, and that is the singleton.
Ideally your settings should be a member variable in a high level location, for example the application object which owns the webpages you are spawning. The pages can then ask the app for the settings, or the application can pass the settings as pages are constructed.
One way to approach this problem, is to flog it off as a DAL problem.
Whatever class / web page, etc. needs to use config settings should declare a dependency on an IConfigSettingsService (factory/repository/whatever-you-like-to-call-them).
private IConfigSettingsService _configSettingsService;
public WebPage(IConfigSettingsService configSettingsService)
{
_configSettingsService = configSettingsService;
}
So your class would get settings like this:
ConfigSettings _configSettings = _configSettingsService.GetTheOnlySettings();
the ConfigSettingsService implementation would have a dependency which is Dal class. How would that Dal populate the ConfigSettings object? Who cares.
Maybe it would populate a ConfigSettings from a database or .config xml file, every time.
Maybe it do that the first time but then populate a static _configSettings for subsequent calls.
Maybe it would get the settings from Redis. If something indicates the settings have changed then the dal, or something external, can update Redis. (This approach will be useful if you have more than one app using the settings.
Whatever it does, your only dependency is a non-singleton service interface. That is very easy to mock. In your tests you can have it return a ConfigSettings with whatever you want in it).
In reality it would more likely be MyPageBase which has the IConfigSettingsService dependency, but it could just as easily be a web service, windows service, MVC somewhatsit, or all of the above.

Looking for Ninject equivalent of StructureMap's ObjectFactory.GetInstance() method

I'm using Ninject in an MVC project and I've used the autoregistration features in Ninject.Mvc and have my bindings set up in my application class. However, I have a place where I want to create an instance separate from those bindings. In StructureMap, you can do var foo = ObjectFactory.GetInstance<IFoo>(); and it will resolve it for you. Is there an equivalent in Ninject 2? I can't seem to find it anywhere.
AFAIK, NInject doesn't have static method like this so all resolving should go to some kernel.
But you can implement it easily;
class ObjectFactory
{
static IKernel kernel = new StandardKernel(.....);
public static T GetInstance<T>()
{
return kernel.Get<T>();
}
}
Although, IMO, NInject is much more useful as DI container than as service locator.
You can also use Common Service Locator as an abstraction layer for Ninject IOC which offers what you want. The advantage is that you can later switch container if it does not fit your needs anymore.
In your code you can use something like this:
ServiceLocator.Current.GetInstance<Type>();