2017-03-07 4 views
0

첫 번째 호출에서 데이터베이스에서 일부 데이터를 가져오고이 클래스에 대한 후속 호출이 응용 프로그램의 수명 동안 동일한 데이터를 반환하는 클래스를 구현하려고 시도하고 있는데도이 클래스의 새 인스턴스는 다음과 같습니다. 라는. 이것이 가능한가?Autofac 클래스 전용 구현

여기 내 샘플 시도입니다. 문제는 Object not set to an instance of the Object입니다.

Public Class session 
    Implements IContainerProviderAccessor 

    Shared _containerProvider As IContainerProvider 
    Private _IUserSessionService As IUserSessionService ' interface to stores data 
    Public Property Usersession As IUserSessionService 
     Get 
      Return _IUserSessionService 
     End Get 
     Set(value As IUserSessionService) 
      _IUserSessionService = value 
     End Set 
    End Property 

    Public ReadOnly Property ContainerProvider As IContainerProvider Implements IContainerProviderAccessor.ContainerProvider 
     Get 
      Return _containerProvider 
     End Get 
    End Property 


    Public Function GetConnection() As String 
     Dim UserSessionDetail As New UserSessionDetails 
     ' Do we have a container if not register one 
     If IsNothing(_containerProvider) Then 
      RegisterConnection() 
      Dim UserSessionDetail As New UserSessionDetails 
      UserSessionDetail.connection_string = GoAndGetOneFromOtherSource 
      Usersession.AddSession(UserSessionDetail) 
      Return UserSessionDetail.connection_string 
     Else 
      Usersession.GetUserSession() 
      Return UserSessionDetail.connection_string 
     End If 
    End Function 


    Private Sub RegisterConnection() 
     Dim builder As ContainerBuilder = New ContainerBuilder() 

     builder.RegisterType(Of UserSessionService).As(Of IUserSessionService).InstancePerRequest() 

     'Auto Fac Binding 
     _containerProvider = New ContainerProvider(builder.Build()) 

    End Sub 

End Class 
+0

그래 물론이 가능, Autofac의 관점에서 ... 이미 데이터가있는 경우 그래서를 반환하는 경우 다음을 인출 할하지 않을 경우, 볼 – Trey

+1

을 확인, 정적 데이터 및 방법을 정의,이 싱글 톤 객체에 의존하거나 객체를 싱글 톤으로 만드는 방법으로 수행 할 수 있습니다. 다른 객체가'session'에 대한 의존성을 선언 할 때마다 동일한 객체를 사용할 것입니다. 솔직히 말해서, 이것은 나에게 조금 혼란스러워 보입니다. 'IContainerProviderAccessor'는 HttpApplication 객체를 확장하는데 사용되어야합니다. 아마도 [통합 문서] (http://autofac.readthedocs.io/en/latest/integration/webforms.html)를 검토하십시오. –

답변

0

당신은 (내가 기본 Session 클래스와 충돌을 가지고 SessionStore 대신 Session의 사용) Autofac에서 싱글로 당신의 IUserSessionService를 등록하고 SessionStore 클래스 생성자에 주입 할 필요가있다. 이렇게하면 SessionStore 인스턴스를 얻을 때마다 IUserSessionService 구현의 인스턴스가 하나만 사용됩니다.

public class SessionStore : ISessionStore 
{ 
    public SessionStore(IUserSessionService userSessionService) 
    { 
     this._userSessionService = userSessionService; 
    }  

    private readonly IUserSessionService _userSessionService; 

    public String ConnectionString 
    { 
     get 
     { 
      // do what you want with _userSessionService 
     } 
    } 
} 

및 등록은 다음과 같이 표시됩니다

당신의 SessionStore은 다음과 같이됩니다.

builder.RegisterType<XUserSessionService>().As<IUserSessionService>().SingleInstance(); 
builder.RegisterType<SessionStore>().As<ISessionStore>().InstancePerRequest(); 

자세한 내용은 문서에서 structuring pages and user controls for Dependency Injection를 참조 ISessionStore 인스턴스가 당신이 Page 객체의 속성 주입을 사용할 수 있습니다 얻으려면.

// MyPage.aspx.cs 
public partial class MyPage : Page 
{ 
    // This property will be set for you by the PropertyInjectionModule. 
    public ISessionStore SessionStore { get; set; } 

    protected void Page_Load(object sender, EventArgs e) 
    { 
    // Now you can use the property that was set for you. 
    label1.Text = this.SessionStore.ConnectionString; 
    } 
} 

아니면 페이지의 외부 세션에 액세스하려고하면 IContainerProviderAccessor에 액세스 할 수 있습니다.

ILifetimeScope lifetimeScope = ((IContainerProviderAccessor)HttpContext.Current.ApplicationInstance).ContainerProvider.RequestLifetime; 
ISession session = lifetimeScope.Resolve<ISessionStore>();