Entering Autofac Properties

I am trying to change an Asp.Net MVC3 project to use Autofac to inject a service into my controllers. So far it has been pretty simple. All my services have the Telerik OpenAccess db property, which I insert through the constructors (in the base class of the service). And my controllers have constructor properties for services that are also injected.

I have a class called AuditInfo that encapsulates the checked properties of the controller:

public class AuditInfo
{      
    public string RemoteAddress { get; set; }

    public string XForwardedFor { get; set; }

    public Guid UserId { get; set; }

    public string UserName { get; set; }
}

The My OpenAccess db property in my service classes must have an instance of this class inserted into it in order to use it as audit information in various database calls.

, , Application_Start, , RemoteAddress XForwardedFor OnActionExecuting, , Request.

OnActionExecuting BaseController :

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    base.OnActionExecuting(filterContext);
    db.AuditInfo = AuditInfo;                                      
}

public AuditInfo AuditInfo
{
    get
    {
        return new AuditInfo()
        {
            RemoteAddress = this.Request.ServerVariables["REMOTE_ADDR"],
            XForwardedFor = this.Request.ServerVariables["X_FORWARDED_FOR"],
            UserId = this.UserId,
            UserName = this.UserName
        };
    }
}

- /:

  • OpenAccess db OnActionExecuting.
  • , AuditInfo AuditInfo -
  • , AuditInfo, db-, - db AuditInfo. BUT AuditInfo , . = > ...

autofac AuditInfo , ? - ?

, AuditInfo , ip/user info?

+5
2

Autofac MVC Integration HttpRequestBase . HttpContext.Current.Request.

Autofac HttpContext.Current . , MVC HttpContext.Current , ( Autofac) . , - " " HttpContext.Current.Request , . ( , )

, IAuditInfoFactory, , HttpRequestBase HttpContext.Current, .

, , - AuditInfo, :

builder.Register(c => c.Resolve<IAuditInfoFactory>().CreateNew())
    .As<AuditInfo>()
    .InstancePerHttpRequest();
+2

: factory.

IAuditInfoFactory , , :

public class HttpRequestAuditInfoFactory : IAuditInfoFactory
{
    // Service for requesting information about the current user.
    private readonly ICurrentUserServices user;

    public HttpRequestAuditInfoFactory(ICurrentUserServices user)
    {
        this.user = user;
    }

    AuditInfo IAuditInfoFactory.CreateNew()
    {
        var req = HttpContext.Current.Request;

        return new AuditInfo()
        {
            RemoteAddress = req.ServerVariables["REMOTE_ADDR"],
            XForwardedFor = req.ServerVariables["X_FORWARDED_FOR"],
            UserId = this.user.UserId,
            UserName = this.user.UserName
        };
    }
}

:

builder.RegisterType<HttpRequestAuditInfoFactory>()
    .As<IAuditInfoFactory>()
    .SingleInstance();

+2

All Articles