MS统一容器

时间:2016-01-11 16:03:24

标签: c# unity-container

我有一个接口IInterface,它看起来像下面的那样 -

public interface IInterface             
{      
  void SomeMethod1();      
  void SomeMethod2();  
  void SomeMethod3();   
  .                    
  .                    
  .                     
}       

其中一个实现类似于 -

public class Implementation : IInterface         
{     
  private Object obj;
  public Implementation(Object obj)      
  {        
       this.obj = obj;
      // Do Something           
  }        

  public void SomeMethod1()    
  {    
     lock(obj)
     {
        // Do Something   
     }     
  }    

  public void SomeMethod2()    
  {    
     // Do Something   
  } 

  public void SomeMethod3()    
  {    
     lock(obj)
     {
        // Do Something   
     }      
  } 
  .                            
  .                            
  .                                    
}     

如何在通过统一配置注册具有类型IInterface的Implementation类时传递Object类型的静态只读实例?

1 个答案:

答案 0 :(得分:0)

我首选的方法可能是创建一个用于创建IInterface s

的工厂
public interface IInterface
{
  void SomeMethod1(); 
}

public interface IInterfaceFactory
{
    IInterface CreateInterface();
}

public class StandardInterfaceFactory : IInterfaceFactory
{
    // Define your static lock object here. Other customers 
    // can define their own IInterfaceFactory to use a 
    // different lock object.
    private static readonly object lockObject = new object();

    public IInterface CreateInterface()
    {
        return new StandardInterface(lockObject);
    }
}

public class StandardInterface : IInterface
{
    private readonly object lockObject;

    public StandardInterface(object lockObject)
    {
        this.lockObject = lockObject;
    }

    public void SomeMethod1()
    {
        lock (this.lockObject)
        {
            Console.WriteLine("I've locked on " + lockObject);
        }
    }
}

您的统一配置和客户端代码将如下所示。

void Main()
{
    IUnityContainer container = new UnityContainer();

    // This mapping can be done trivially in XML configuration.
    // Left as an exercise for the reader :)
    container.RegisterType<IInterfaceFactory, StandardInterfaceFactory>();

    IInterfaceFactory factory = container.Resolve<IInterfaceFactory>();

    IInterface myInterface = factory.CreateInterface();

    myInterface.SomeMethod1();
}