2017-07-03 73 views
0

我只是想知道是否可以在我的服務中調用方法,當我註冊時。Autofac:註冊組件時調用初始化方法

public interface IDataService 
{ 
    User GetUserById(int id); 
    void SaveUser(int id, User user); 
} 

public class DataService : IDataService 
{ 
    public User GetUserById(int id) 
    { 
     // do stuff 
    }; 

    public void SaveUser(int id, User user) 
    { 
     // do stuff 
    }; 

    public void InitialiseService() { }; 
} 

當我註冊這個組件時,是否可以調用InitialiseService以便我的服務被初始化?

builder.RegisterType<DataService>() 
        .Keyed<IDataService>(FiberModule.Key_DoNotSerialize) 
        .AsImplementedInterfaces() 
        .SingleInstance(); 
+0

https://stackoverflow.com/questions/2320536/how-to-carry-out- custom-initialisation-with-autofac –

回答

2

可以使用OnActivating僞事件:

builder.RegisterType<DataService>() 
     .Keyed<IDataService>(FiberModule.Key_DoNotSerialize) 
     .AsImplementedInterfaces() 
     .OnActivating(e => e.Instance.InitialiseService()) 
     .SingleInstance(); 

它看起來像你正在做一個單身,所以你也可以考慮實施IStartable界面,將自動被Autofac

實例化
public class DataService : IDataService, IStartable 
{ 
    public User GetUserById(int id) 
    { 
     // do stuff 
    } 

    public void SaveUser(int id, User user) 
    { 
     // do stuff 
    } 

    public void Start() 
    { 

    } 
} 

或使用AutoActivate方法讓Autofac自動創建實例。

builder.RegisterType<DataService>() 
     .Keyed<IDataService>(FiberModule.Key_DoNotSerialize) 
     .AsImplementedInterfaces() 
     .AutoActivate() 
     .SingleInstance(); 

,或者使用在ContainerBuilderRegisterBuildCallback方法做事的容器已建成

builder.RegisterType<DataService>() 
     .Keyed<IDataService>(FiberModule.Key_DoNotSerialize) 
     .AsImplementedInterfaces() 
     .SingleInstance(); 

builder.RegisterBuildCallback(c => c.Resolve<IDataSerialize>().Initialise()); 
+0

容器構建回調是第三種選擇。 http://autofac.readthedocs.io/en/latest/lifetime/startup.html#container-build-callbacks –

相關問題