N
N
Nikita2012-05-28 13:14:13
.NET
Nikita, 2012-05-28 13:14:13

Asp.net mvc3 -> Autofac question?

Good afternoon, hackers.
Please tell me how can I do the following:
There is a UserManager class, it has a constructor that accepts a certain interface (for example, ItblUsersRepository). How can I resolve this interface every time I call UserManager other than setting DependencyResolver.Current.GetService in the default constructor? Can the code below be automated somehow or set from global.asax? asp.net mvc3 app if that matters.
Now it looks something like this:

public class UserManager <br>
    {<br>
        private ItblUsersRepository _userRepo;<br><br><br>
        public UserManager()<br>
        {<br><br>
            _userRepo = DependencyResolver.Current.GetService<ItblUsersRepository>();<br>
        }<br><br><br>
        public UserManager(ItblUsersRepository userRepo)<br>
        {<br>
            _userRepo = userRepo;<br>
        }<br>
}<br>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Georgy Mogelashvili, 2012-05-28
@glamcoder

if I understand the question correctly, then you can do this through the
Global.asax.cs controller factory:

protected void Application_Start()
{
    // ...

    ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
}

NinjectControllerFactory.cs:
public class NinjectControllerFactory : DefaultControllerFactory
    {
        private IKernel _ninjectKernel;

        public NinjectControllerFactory()
        {
            _ninjectKernel = new StandardKernel();
            AddBindings();
        }

        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
        {
            return controllerType == null
                       ? null
                       : (IController)_ninjectKernel.Get(controllerType);
        }

        private void AddBindings()
        {
            _ninjectKernel.Bind<ISomeInterface>().To<SomeClass>();            
        }
    }

controller:
public class MyController : Controller
{
        public MyController(ISomeInterface inter)
        {
            _inter = inter;
        }
        
        // ...
}

Example taken from Pro ASP NET MVC 3 Framework by Adam Freeman and Steven Sanderson

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question