Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IoC - Unity, how RegisterInstance Works, Am I right?

I am implementing Ioc and there are few things i want to make sure are right.

  1. If I use RegisterInstance, on resolving it will always return the singleton object?
  2. BootStrapper will be loaded in Global.asax or some place where it will be loaded initially, which means all the instances will be singleton?

But i want to know how to
1. Create a separate instance per resolve, PerResolve wont work with RegisterInstance, it works only with RegisterType.
2. If I make dependent object as static property, it will work the same way, if i am able to create separate instance per resolve?

please help?

public class ClientUser : UserServiceBase, IClientUser
{
    private  IDataServiceManager _dataServiceManager;
    public ClientUser()
    {

    }

    private IDataServiceManager DataServiceMgr
    {
        get
        {
            if (_dataServiceManager == null)
                _dataServiceManager = ProjectContainer.Instance.Resolve<IDataServiceManager>();

            return _dataServiceManager;
        }
    }    
like image 979
Waqas Avatar asked Mar 22 '11 16:03

Waqas


1 Answers

You can't use RegisterInstance if you want PerResolve instancing. Either use RegisterInstance which will return always the same instance of the object (that is the point of registering instance) or use RegisterType and define PerResolveLifetimeManager.

RegisterInstance by default uses ContainerControlledLifetimeManager. The only other meaningfull lifetime manager for RegisterInstance is ExternallyControlledLifetimeManager.

TransientLifetimeManager and PerResolveLifetimeManager don't make sense because these lifetimes must create new instance each time you call Resolve.

PerThreadLifetimeManager is useless in scenarios where you don't control threading .

like image 151
Ladislav Mrnka Avatar answered Sep 20 '22 18:09

Ladislav Mrnka