Autofac - controllers - services

Topics: Core, Writing modules
Jan 16, 2014 at 11:33 AM
Hi,
I got a little bit confused on this.

I have this service class...
    public class EmailerService : Emailer.Services.IEmailerService
    {
        private readonly IOrchardServices _orchardServices;
        private readonly INotifier _notifier;
        private readonly IRepository<SentNotificationRecord> _sentNotificationEmailRepository;

        public ILogger Logger { get; set; }
        public Localizer T { get; set; }

        public EmailerService(IOrchardServices orchardServices, INotifier notifier, IRepository<SentNotificationRecord> sentNotificationEmailRepository)
        {
            _notifier = notifier;
            _orchardServices = orchardServices;
            _sentNotificationEmailRepository = sentNotificationEmailRepository;
            Logger = NullLogger.Instance;
        }
//some methods
}
The IEmailerService interface inherits from IDependency of course.

If I want to use the service class in a controller, then no problem, I put the service's related interface in the controller's constructor and stop.

What if I want to instantiate the service class myself passing all the parameters in?

It seems that having the IEmailerService interface passed to my controller constructor is the only way to instantiate and use the service too (maybe because controllers are automatically instantiated by Orchard, and I never have to pass params there).

As, of course, it's impossible to instantiate interfaces (i.e. IRepository<someclass>) I can't prepare my params before passing them.

I there a way to invoke explicitly some Autofac action to explicitly instantiate the service class?
Which is the best way to proceed here?

Many thanks for your time guys.
Jan 16, 2014 at 1:25 PM
You can call WorkContext.Resolve<T>() with T being your interface type to resolve the dependency. You can get a WorkContext handle with a IOrchardServices instance, or with a IWorkContextAccessor instance, and it's available in view templates where you don't have a constructor.

If you have all the parameters to pass to the constructor of a service class, of course you can call the constructor but it doesn't make much sense to me, since to get the constructor parameters, you will need to resolve other dependencies for parameters.


Jan 16, 2014 at 3:58 PM
Ok.
Of course I don't have "all the parameters to pass to the constructor of a service class", that's why I was looking for some Autofac facility.

Many thanks.