0

I'm working with autofac. So far i resolve all my dependencies with constructor injection.

There is a case where i get stuck:

Considering the given customer class:

public class Customer : ICustomer
{
    public string Name { get; set; }

    private int ExternId { get; set; }

    public IExternalIdProvider externalIdProvider { get; set; }

    public Customer()
    {
            this.externalIdProvider = new ConcreteIdProvider(this);
    }

    public BevorSave()
    {
        this.ExternId = externalIdProvider.GetNextId();
    }
}

In Order to create a new customer object based on a request or gui action. I use the new Operator. However - There is an IdProvider within the CustomerClass i want to inject. (as property).

If the Customer would be resolved by the ioC Container i would use a configuration like:

builder.RegisterType<ConcreteIdProvider>().As<IExternalIdProvider>();
builder.RegisterType<Customer>().As<ICustomer>()
       .OnActivated(ae =>
            {
              IExternalIdProvider idProvider = 
                ae.Context.Resolve<IExternalIdProvider>(TypedParameter.From(ae.Instance));
              ae.Instance.externalIdProvider = idProvider;
            });

My Question is: How can I inject the behaviour of the ExternalIdProvider in the Customer? (using autofac)

This article shows a sample, how this would be done with a service locator: http://blogs.msdn.com/b/simonince/archive/2008/06/30/dependency-injection-is-dead.aspx

Thanks for your help.

flo scheiwiller
  • 2,706
  • 2
  • 17
  • 15
  • You might need to clarify what you're trying to do with a [non-functional] code snippet. If you just want to have properties injected, you can use Autofac's PropertiesAutowired function when you register Customer... but I'm guessing that's not what you're after. The example you linked to shows use of PostSharp for Aspect-Oriented Programming. That's the key to that example - not the dependency resolution framework. – Travis Illig Apr 09 '12 at 15:12

1 Answers1

0

You should reconsider having behavior on your entities. Having behavior in your entities forces you to do dependency injection on them, and this leads to an awkward situation, which you already noticed. Take a look at this related SO question and Mark Seemann's great answer.

So instead of having these operations on the Customer class, move them to an repository class. Other patterns to look at are unit of work, commands and queries.

Community
  • 1
  • 1
Steven
  • 166,672
  • 24
  • 332
  • 435