D
D
Dmitry2013-06-04 13:39:18
ASP.NET
Dmitry, 2013-06-04 13:39:18

Autofac - automatic controller injections?

I dig with examples, articles - I just can’t understand.
Here we have Autofac registration (the functionality is primitive, purely to learn).

public interface ISiteInfo
    {
        string GetReffer(Controller controller);
    }

    public class SiteInfo : ISiteInfo
    {
        public string GetReffer(Controller controller)
        {
            if (controller.Request.UrlReferrer != null)
            {
                return controller.Request.UrlReferrer.ToString();
            }
            return "";
        }
    }

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof (MvcApplication).Assembly);
            builder.RegisterType<SiteInfo>();            
            builder.Register<ISiteInfo>(x => x.Resolve<SiteInfo>());
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        [...]
        }
    }

There is. Fine. But how to use auto-creation of the desired class instance?
In ninject it would look like this:
public class QuestsListController : Controller
    {
        [Inject]
        public ISiteInfo InfoObject { get; set; }
        [...]
    }

But I didn’t understand how to implement such an option just as beautifully with autofac - you have to use this one.
public class QuestsListController : Controller
    {
        public ISiteInfo InfoObject { get; set; }

        public QuestsListController(SiteInfo _InfoObject)
        {
            InfoObject = _InfoObject;
        }
        [...]
    }

Whatever is beautiful
How to deal with such things? Or am I just not understanding something?
Still, according to the tests that came across to me, Ninject is much inferior in speed to the rest.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrei Smirnov, 2013-06-08
@pinebit

I can only advise you to look towards Unity (Microsoft Enterprise Library) and [InjectionConstructor]. When you get to testing your classes, you will understand why constructor dependency injection is the best solution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question