Question

I am using Autofac for IoC in ASP .Net MVC 4 app.

I am not able to figure out why the dependency resolver is passing the same value for different parameters when resolving a dependency.

Here is how I am registering:

private void RegisterDependencyResolver()
{
    var builder = new ContainerBuilder();

    builder.RegisterControllers(Assembly.GetExecutingAssembly());

    builder.Register(x => new AESCryptographyService()).As<ICryptographyService>();
    builder.RegisterType<AppContext>().As<IContext>();

    IContainer container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}

Here is how I am resolving IContext:

var factory = _dependencyResolver.GetService<Func<string, string, string, IContext>>();
IContext context = factory(contextToken, hostUrl, request.Url.Authority);

Here is my AppContext:

internal class AppContext : IContext
{
    public AppContext(string contextToken, string hostUrl, string appUrl)
    {
        AppUrl = appUrl;
        HostUrl = hostUrl;
        ContextToken = contextToken;
    }

    public string AppUrl { get; private set; }

    public string ContextToken { get; private set; }

    public string HostUrl { get; private set; }
}

Please have a look at this screenshot. Even though contextToken, hostUrl, and request.Url.Authority have different values, in the constructor of AppContext all the values are set to the value of contextToken.


enter image description here

Was it helpful?

Solution

Figured it out!

I had to replace this:

var factory = _dependencyResolver.GetService<Func<string, string, string, IContext>>();
IContext context = factory(contextToken, hostUrl, request.Url.Authority);

with this:

var context =
    _dependencyResolver.RequestLifetimeScope.Resolve<IContext>(
        new NamedParameter("contextToken", contextToken), 
        new NamedParameter("hostUrl", hostUrl),
        new NamedParameter("appUrl", request.Url.Authority));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top