开发者

asp.net mvc autofac registery and resolver

I am working on ASP.NET MVC 3 application. I am using Autofac as my dependency resolver. I have two projects one core and other UI. In the core project I have an interface which holds information about the logged in user if any. This is inherited in my UI project.

public interface IWebContext
{
  User User {get;set}
  bool IsLoggedIn {get;} 

}

In ui project this is implemented as

public class WebContext :  IWebContext
{
//codes here to get user and islogged in proerty.
}

In the core project I am creating link based on some logic.

public static class ButtonExtension
{
    public static MvcHtmlString EditButton(this HtmlHelper helper, string controller, string action, object id, string text)
    {
        var webContext= how to get IWebContext here.

       if (!webContext.IsLoggedIn)
       {
           return MvcHtmlString.Empty;
       }
        return MvcHtmlString.Create(string.Format("<a href=\"/{0}/{1}/{2}\">{3}</a>", controller, action, id, text));
    }
}

In my global.asax I am registering all my services using IOC static class

 protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterRoutes(RouteTable.Routes);

        IOC.Build();

    }

here is my IOC class.

public static class IOC 
{
    private static IContainer _container;
    public static void Build()
    {

        ContainerBuilder builder = new ContainerBuilder();
        builder.RegisterControllers(Assembly.GetExecutingAssembly());
        builder.Register(c => new WebContext()).As<IWebContext>().SingleInstance();
        builder.Register(c => new 开发者_开发问答ImageServiceLocal()).As<IImageService>().InstancePerHttpRequest();
        builder.RegisterFilterProvider();
        _container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
    }

    public static T Resolve<T>()
    {
        if (_container == null)
            Build();

        return _container.Resolve<T>();


    }


}


var webContext = DependencyResolver.Current.GetRequestLifetimeScope()
                                           .Resolve<IWebContext>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜