3

Trying to use autofac for dependency injection by property.

The instance is always null and there is no dependency injected. Below is class where the property needs to be injected.

public class UserAccount
{
    public IAccountService AccountService { get; set; }

    public string Message()
    {
        return AccountService.Message();
    }
}

I have tried three different ways to inject the property but none was successful

Method 1 :

builder.Register(c => {
                var result = new UserAccount();
                var dep = c.Resolve<IAccountService>();
                result.SetDependency(dep);
                return result;
            });

Method 2 :

builder.RegisterType<UserAccount>().PropertiesAutowired();

Method 3 :

builder.Register(c => new UserAccount { AccountService = c.Resolve<IAccountService>()});

PS : Method injection of above is welcomed.

Steven
  • 166,672
  • 24
  • 332
  • 435
MDT
  • 1,535
  • 3
  • 16
  • 29
  • Is the `UserAccount` object created by Autofac, too? If you create it manually (by using the `new` operator), it will not work, because Autofac is not involved in the object creation. – KBO Nov 22 '18 at 07:44
  • @KBO yes i am manually creating it using new, what should i do then ? – MDT Nov 22 '18 at 08:10
  • Please show the code that shows how you resolve and use `UserAccount`. – Steven Nov 22 '18 at 08:49
  • Possible duplicate of: https://stackoverflow.com/questions/29915192/property-injection-on-attributes – Steven Nov 22 '18 at 10:02
  • Where's the filter attribute mentioned in the question title? What framework is the filter attribute? – Travis Illig Nov 22 '18 at 19:34

2 Answers2

1

You should prevent letting your container create data-centric objects, such as your UserAccount entity. This leads to complicated scenarios, such as the one you are in now.

In general, your DI Container should resolve only components—those are the classes in your system that contain the application's behavior, without having any interesting state. Those types of classes are typically long lived, or at least, longer lived than data-centric objects.

Data-centric objects, like entities, can best be created by hand. Not doing so would either lead to entities with big constructors, which easily causes the constructor over-injection code smell. As remedy, you might fall back on using Property Injection, but this causes a code smell of its own, caused Temporal Coupling.

Instead, a better solution is to:

  1. Create entities by hand, opposed to using a DI Container
  2. Supply dependencies to the entity using Method Injection, opposed to using Property Injection

With Method Injection, your UserAccount would as follows:

// This answer assumes that this class is an domain entity.
public class UserAccount
{
    public Guid Id { get; set; }
    public byte[] PasswordHash { get; set; }

    public string Message(IAccountService accountService)
    {
        if (accountService == null)
            throw new ArgumentNullException(nameof(accountService));

        return accountService.Message();
    }
}

This does move the responsibility of supplying the dependency from the Composition Root to the entity's direct consumer, though. But as discussed above, this is intentional, as the Composition Root in general, and a DI Container in particular, should not be responsible of creating entities and other data-centric, short-lived objects.

This does mean, however, that UserAccount's direct consumer should inject that dependency, and with that, know about existence of the dependency. But as that consumer would be a behavior-centric class, the typical solution is to use Constructor Injection at that stage:

public class UserService : IUserService
{
    private readonly IAccountService accountService;
    private readonly IUserAccountRepository repo;

    public UserService(IAccountService accountService, IUserAccountRepository repo)
    {
        this.accountService = accountService;
        this.repo = repo
    }

    public void DoSomething(Guid id)
    {
        UserAccount entity = this.repo.GetById(id);
        var message = entity.Message(this.accountService);
    }
}
Steven
  • 166,672
  • 24
  • 332
  • 435
  • But this would mean that i have to make a reference of the business layer in my presentation layer in order to access that repository... is that OK? I mean wouldn't that violate layer separation ? Currently the presentation layer only knows about the service layer.. – MDT Nov 22 '18 at 09:27
  • This probably means that you have placed your abstractions in the wrong place, because your presentation layer shouldn't have to depend on the business layer, if it only needs to use its abstractions. Your comment also seems to imply that your presentation layer directly calls `UserAccount.Message`, which would be a violation of layer separation, as the presentation layer should typically not call domain methods directly, but only do so through an interacting layer. – Steven Nov 22 '18 at 09:33
  • So far i have been sucessful with DI and using it in my controllers, but there is a scenario where i have to use the services in my custom mvc filters and for that i have to keep the filters parameter less and which is why i created this class called UserAccount to handle the services for my filter. We trying to create a base for the project. – MDT Nov 22 '18 at 09:49
  • Ahhh, okay. So you're saying that `UserAccount` is _not_ an entity but a component. In that case my answer is not helpful. Instead, your question seems a duplicate of [this q/a](https://stackoverflow.com/questions/29915192/property-injection-on-attributes). – Steven Nov 22 '18 at 10:02
  • So no DI for attributes looks like an invisible dead end? But there are several other articles that mention various methods of Filter injection, especially with ninject. Guess i'll go old school here nothing fancy :) – MDT Nov 22 '18 at 10:28
0

Using method 3, you need to register AccountService, i.e.

        builder.RegisterType<AccountService>().As<IAccountService>();
        builder.Register(c => new UserAccount { AccountService = c.Resolve<IAccountService>()});

And when you use UserAccount, make sure it is created using Autofac.

Phillip Ngan
  • 15,482
  • 8
  • 63
  • 79