Answer the question
In order to leave comments, you need to log in
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));
[...]
}
}
public class QuestsListController : Controller
{
[Inject]
public ISiteInfo InfoObject { get; set; }
[...]
}
public class QuestsListController : Controller
{
public ISiteInfo InfoObject { get; set; }
public QuestsListController(SiteInfo _InfoObject)
{
InfoObject = _InfoObject;
}
[...]
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question