null registration?

523 views
Skip to first unread message

mcintyre321

unread,
Dec 24, 2009, 7:29:04 AM12/24/09
to Autofac
*maybe I'm wrong about this and it already works, but if so I'm doing
it wrong!*

I was wondering if it would be possible to allow null registrations -
i.e. that if I register null as User, constructors with a User
parameters will be considered for resolution, albeit with a null user
value.

When I have things that may or may not be registered (e.g. I have a
User object registered if someone is authenticated, but not for
anonymous web users) I have to create two constructors e.g.

public MyController(User user, ...) { _user = user; }
public MyController(...) this(null, ...) { }

in my Actions I check if the user is null to decide what to do. This
works OK, but once I create another null dependency I have to create
more constructors - in fact 2 ^ (number of null dependencies)
constructors to get all the combinations!

I can get round this by injecting the null object pattern, but I'm not
that keen on it - I like null meaning null!

Nicholas Blumhardt

unread,
Dec 24, 2009, 7:35:21 PM12/24/09
to aut...@googlegroups.com
Howdy,

I'm not a fan of accepting null in constructors since (at least in Autofac's world) a constructor parameter means a mandatory dependency. The more idiomatic way to do this would be to have a nullable User property and set it via property injection if it is available.

There are :) however a few ways to get the behaviour you desire.

For starters if using reflective registrations you can add a parameter:

builder.Register<MyController>().WithArgument("user", null);

To be a bit trickier, you can do something like (pseudocode warning!):

class AllowNullForService<T> : Module
{
  protected override void AttachToComponentRegistration(IComponentRegistration cr)
  {
    cr.Preparing += (s, e) => {
       if (!e.Context.IsRegistered<T>())
          e.Parameters = e.Parameters.Concat(new Parameter[] { TypedParameter.For<T>(null) });
    };
  }
}

builder.RegisterModule(new AllowNullForService<User>());

Could obviously be made more efficient.

There are probably a few other approaches hiding in there too... Let me know if you have trouble with either of these, I haven't run this code :D

Cheers
Nick

2009/12/24 mcintyre321 <mcint...@gmail.com>

--

You received this message because you are subscribed to the Google Groups "Autofac" group.
To post to this group, send email to aut...@googlegroups.com.
To unsubscribe from this group, send email to autofac+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/autofac?hl=en.



Reply all
Reply to author
Forward
0 new messages