jbogard/ContosoUniversity

Use AutoFac instead of StructureMap

TDK1964 opened this issue · 7 comments

Any of you clever chaps ever done this?
I use AF in all my projects and would really like to see an AF version.

Yes, I did.

@AlonAmsalem Thanks for this, very useful. Have you managed to convert other classes in the project?

HtmlHelperExtensions.cs

And this one MvcTransactionFilter.cs

Here's how I implemented the transaction-filter

public class TransactionFilter : IAutofacActionFilter
    {
        public void OnActionExecuting(HttpActionContext actionContext)
        {
            var requestScope = actionContext.Request.GetDependencyScope();

            var context = requestScope.GetService(typeof(CloudinatorContext)) as CloudinatorContext;

            context?.BeginTransaction();
        }

        public void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var requestScope = actionExecutedContext.Request.GetDependencyScope();

            var context = requestScope.GetService(typeof(CloudinatorContext)) as CloudinatorContext;

            context?.CloseTransaction(actionExecutedContext.Exception);
        }
    }

I don't use the Html-Helper-Extensions because my client-side is a standalone AngularJS

Here's my Global.asax, you'll need it for the transaction-filter

    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            var container = IoC.Initialize();

            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            GlobalConfiguration.Configure(WebApiConfig.Register);

            AutoMapperBootstrapper.Initialize(container);

            AreaRegistration.RegisterAllAreas();
        }
    }
private static IElementGenerator<T> GetGenerator<T>(T model) where T : class
        {
            var library =
                StructuremapMvc.ParentScope.CurrentNestedContainer.GetInstance<HtmlConventionLibrary>();
            return ElementGenerator<T>.For(library, t => StructuremapMvc.ParentScope.CurrentNestedContainer.GetInstance(t), model);
        }

I'm still having problems converting this to Autofac. I tried this but it doesn't work.

private static IElementGenerator<T> GetGenerator<T>(T model) where T : class
        {
            var library = AutofacDependencyResolver.Current.RequestLifetimeScope.Resolve<HtmlConventionLibrary>();
            return ElementGenerator<T>.For(library, t => AutofacDependencyResolver.Current.RequestLifetimeScope.Resolve(t), model);
        }