Posts Tagged: .net


19
Jul 10

Injecting properties in Ninject 2 without “[Inject]” attribute

Dependency Injection is a great way to remove dependencies while having an lightweight container (a “service locator”) wiring up the application’s components and resolving instances and relationships. But Ninject, one of the dependency injection solutions for .Net, adds another unwanted dependency: to the container itself.
A dependency to Ninject is needed when initializing the container and obtaining entities, although the latest can be minimized using the Common Service Locator library to create an abstraction to most of the currently available dependency injection implementations. But Ninject also adds a dependency to the classes that will be initialized by the container, this is not desired and should be avoided at all cost and these classes shouldn’t be aware how they’ll be instantiated.
Ninject defines an attribute (Inject) used as an hint by the Ninject kernel to know where to inject the instantiated objects; although this attribute is optional for Constructor Injection is mandatory for Property Injection and Method Injection.

// My class where Ninject
// will create and inject
// an instance of IWeapon
public class Samurai
{
    //  This is a Ninject attribute,
    //  if we switch to another
    //  DI container the code will break
    [Inject]
    public IWeapon Context { get; set; }
}

Fortunately Ninject is highly customizable and allows to change that behavior, the plan is to create a custom attribute and configure it so that Ninject can use it the same way it uses the Inject attribute. The usage will be similar but all the dependencies will be to local classes, the custom attribute can be something as simple as this:

public class InjectHereAttribute : Attribute
{
}

The class will now look like this:

public class Samurai
{
    //  Now there's no external dependency,
    //
    //
    [InjectHere]
    public IWeapon Context { get; set; }
}

Now Ninject must be configured to use the custom attribute, this can be done by creating an implementation of IInjectionHeuristic that recognizes the custom attribute:

public class CustomInjectionHeuristic : NinjectComponent, IInjectionHeuristic, INinjectComponent, IDisposable
{
    public new bool ShouldInject(MemberInfo member)
    {
        return member.IsDefined(
          typeof(InjectHereAttribute),
          true);
    }
}

And finally add this behavior to the Ninject Kernel using the Components collection, it will run along the existing components, namely the default implementation of IInjectionHeuristic, which means either the default or the custom attribute can be used.


// Add custom inject heuristic
kernel.Components.Add<IInjectionHeuristic, CustomInjectionHeuristic>();

16
Jul 10

Links for 2010-06-29 through 2010-07-16

These are my shared links for 2010-06-29 through 2010-07-16:


5
Feb 10

Links for 2010-02-5

These are my shared links for 2010-02-5

Two .NET 4.0 lesser-known features [Just another Software Engineer]

Improved Unit Testing and built-in Caching (outside the System.Web assemblies)
shared in delicious, tags:.net programming shared


35 Google open-source projects that you probably don’t know [0x1fff]

shared in delicious, tags:google software opensource shared


What’s New in ASP.NET MVC 2.0? [CodeGuru]

shared in delicious, tags:.net aspnetmvc programming internet shared


25
Feb 09

Spam really gets everywhere, even dotnetkicks

dotnetkicks

Spam really gets everywhere, the screenshot on the right is from the Tags box in the front page of DotNetKicks, a Digg-like online community dedicated to .Net programmers.

 

 

 

 

 

Technorati Tags: ,

11
Feb 09

on unity injection attributes

Unity is a pretty neat piece of work, it’s a simple and straightforward dependency injection container and it gets the job done, which is all you want from any implementation like this.

If someone’s trying to go beyond the “get an implementation instance for a given interface” examples found in most of the tutorials then proper dependency injection will be the way to go. This means returning the proper instance for the given interface, but also properly the objects that instance needs, and also the objects needed by those objects, and this could go on forever. Unity can do this almost automatically, but to do so it may need hints on how objects should be created, specially to choose the right constructor when multiple are available (by default will choose the fatest of them all).

One of the ways this problem is solved is using an attribute that indicates which constructor should be used (the same is valid for either properties and method calls), as shown below:

public class MyClass
{
  public MyObject(SomeOtherClass myObjA)
  {
    ...
  }

  [InjectionConstructor]
  public MyObject(MyDependentClass myObjB)
  {
    ...
  }
} 

The problem is: Unity, and all other dependency injection containers, want to solve a simple issue: reduce coupling between modules, classes, etc. That’s achieved by removing the dependency to the proper implementation, you only have to know the contract to use (the interface) and the dependency injection container will return the proper implementation, whatever that may be. But, by doing this we’re adding another dependency: to the dependency injection container implementation (like Unity), and while this is reasonable for the class that needs to use the container is not so reasonable for the classes the container will use.

Take the code sample above: MyClass is just a plain class, by adding the InjectionConstructor attribute we’re adding a needless dependency because that class will never use Unity, it will be used by Unity. For me using this can be a design flaw that goes against what dependency injection is supposed to achieve. A safer, but more time consuming, way to get around this is to explicitly configure those dependencies (either in design time or run time) instead of letting Unity try to figure them out.

 

Technorati Tags: ,,,,

Share this: 


19
Nov 08

The Future of WCF

“WCF started with a clear bias towards SOAP, WS-* protocols, and other heavyweight standards that were being popularized at the time but had not been ubiquitously adopted.
(…)
I didn’t believe though that you could force the world to use a single approach for building web services.”

Nicholas Allen

Windows Communication Foundation has to be one of the most interesting pieces of the .Net universe released in recent years, mostly for being a huge improvement over the previous web service model in .Net. So when one the minds behind WCF writes about the framework’s future it’s certainly worth a closer look.

The Future of WCF, Part 1
The Future of WCF, Part 2


30
May 08

The Perils of GetHashCode, continued…

Some time ago I wrote about GetHashCode method and now Paulo Morgado has also faced some “hash related” issues to deal with (also in Portuguese). Again, the reminder should be not rely heavily on GetHashCode.


9
May 08

The Perils of GetHashCode

Recently I ran into some unexpected, and rather strange, issues on an application server using the Enterprise Library 2.0 Cache Application Block. Apparently there were occurring some strange collisions while retrieving the data from CacheData (the table where the cached data is stored) where the same cache key was having multiple entries, something the Dictionary container where the data is stored isn’t too happy about. The guys at Patterns and Practices, for performance issues, don’t use the cache key as a primary key for that table, but a much more efficient and more easily indexable” integer, which, in this case, is being calculated using the GetHashCode of the cache key. Usually the GetHashCodeimplementation isn’t a fully blown hash algorithm (unlike the more robust MD5 or SHA) so I allways doubted of the uniqueness, particularly in this case where the application server was moved from a 32 bit to a 64 bit architecture, nothing a quick trip do the good old MSDN wouldn’t confirm:

Remarks

The behavior of GetHashCode is dependent on its implementation, which might change from one version of the common language runtime to another. A reason why this might happen is to improve the performance of GetHashCode.

This basically means you shouldn’t trust GetHashCode, because the result for a given string can, and surely will, be different depending where you are calculating it, namely between 32 and 64 bit architectures. The main lesson to be learnt here is GetHashCode, either for String or any other type, should only be used for disambiguation of entities in runtime.


8
Feb 08

TDD Anti-Patterns

James Carr has compiled a pretty little list of Test Driven Development Anti-Patterns and posted it some time ago in his blog. I have to admit I’ve done some of them once or twice.

TDD Anti-Patterns [via ISerializable]

Technorati Tags: , ,


23
Jan 08

Configuration Section Designer

Jelle Druyts has released a neat little tool for Visual Studio that allows to easily design and visualize the configuration for a .Net solution, without messing around with ConfigurationSection and ConfigurationElement source files, which is quite handy when things become a bit more complicated. It’s still is in an early stage, but it looks rather promising.

Configuration Section Designer