2017-07-03 7 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-を構築された後のことを行うContainerBuilderRegisterBuildCallbackメソッドを使用しますcustom-initialisation-with-autofac –

答えて

2

あなたはOnActivating擬似イベントを使用することができます。あなたも自動的に Autofac

によってインスタンス化されますIStartableインタフェースを実装検討することができるので、あなたがシングルトンをやっているように見える

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

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(); 

またはコンテナが

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

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

コンテナビルドコールバックは3番目のオプションです。 http://autofac.readthedocs.io/en/latest/lifetime/startup.html#container-build-callbacks –

関連する問題