Unity IOC Buildup vs Resolve?

后端 未结 2 1466
抹茶落季
抹茶落季 2021-01-03 22:03

I was wondering when do I use buildup and when do I use resolve, when using the Unity IOC.

And when do I call teardown?

Thanks

2条回答
  •  囚心锁ツ
    2021-01-03 22:23

    Resolve is used when you want the Unity container to construct the instance (a new one just when you need it or an pre-existing singleton), inject its dependencies and hand you the reference to the object.

    BuildUp is used when you already have an instance of the object and want the container to just resolve and inject its dependencies.

    Teardown is the opposite of BuildUp. You can pass your object to the Teardown method of the container to shut down / clean up / whatever you want. The existing container behavior does nothing at Teardown time, but extensions can be written to take advantage of this. You can also make your objects implement IDisposable, and the container will call Dispose() on your object when it is disposed itself.

    IMyService service = container.Resolve(); // New service or pre-existing singleton
    
    IMyService service = GetMyService(); // Get the instance from some source
    container.BuildUp(service); // Inject dependencies
    container.Teardown(service); // Clean-up
    

提交回复
热议问题