2017-03-29 71 views
1

我试图在我的WebApi2应用程序上实现UNITY。 问题是我正在使用现有的SqlConnection,具体取决于在资源的URL中找到的标识符。 所以我需要请求URI中提供的标识符来创建我的上下文。 是否可以从请求URI获取{dbIdentifier},并将其解析为MyRepo的构造函数?Web Api OWIN Host with Unity

的请求USI的样子:/ API/{dbIdentifier}/{控制器}/{ID}

结构看起来像...

Request POST /api/myDbIdentifier/my/ + PAYLOAD data 

Controller: 
public class MyController : ApiController 
{ 
    private readonly IRepo _repo; 

    public MyController(IRepo repo) 
    { 
     _repo = repo; 
    } 
} 

Repo: 
public class MyRepo : IRepo 
{ 
    private readonly MyContext _context; 

    public MyRepo(string dbIdentifier) 
    { 
     _context = new MyContext(GetConnection(dbIdentifier)); 
    } 

    public void Insert(string s) 
    { 
     //Inserting string in context and save changes 
    } 

    private DbConnection(string id) 
    { 
     //psudo find connecion from pool, and return instance of DbConnection... 
    } 
} 

public interface IRepo 
{ 
    void Insert(string s); 
} 

Context: 
public class MyContext : DbContext 
{ 
    public MyContext(DbConnection exitingConnection) : base(existingConnection, true) 
    { } 
} 

顺便说一下,这是我第一次玩与WebApi和Unity在一起,所以请忍受我的无知。

我的代码

修订团结一部分...

UnityResolver(从https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection拍摄):

public class UnityResolver : IDependencyResolver 
{ 
    protected IUnityContainer Container; 

    public UnityResolver(IUnityContainer container) 
    { 
     if (container == null) 
     { 
      throw new ArgumentNullException(nameof(container), "Please provider an IUnityContainer."); 
     } 
     Container = container; 
    } 

    public void Dispose() 
    { 
     Container.Dispose(); 
    } 

    public object GetService(Type serviceType) 
    { 
     try 
     { 
      return Container.Resolve(serviceType); 
     } 
     catch (ResolutionFailedException) 
     { 
      return null; 
     } 
    } 

    public IEnumerable<object> GetServices(Type serviceType) 
    { 
     try 
     { 
      return Container.ResolveAll(serviceType); 
     } 
     catch (Exception) 
     { 
      return new List<object>(); 
     } 
    } 

    public IDependencyScope BeginScope() 
    { 
     return new UnityResolver(Container.CreateChildContainer()); 
    } 
} 

统一注册参加我的启动:

public static void Register(HttpConfiguration config) 
{ 
    // Configuring DI Container fo IoC (Invert of Control) 
    var container = new UnityContainer(); 
    container.RegisterType<IRepo, MyRepo>(new HierarchicalLifetimeManager()); 
    config.DependencyResolver = new UnityResolver(container); 
} 

回答

1

你可以尝试以下方法:

1)创建一个DelegatingHandler你可以在哪里acc ESS HtppRequestMessage.RequestUri

2)从乌里

3)裹dbIdentifier提取dbIdentifier与一个类(例如DbIdentifier),并使用HierarchicalLifetimeManager

4团结注册它)还记得在owin注册处理程序:

httpConfiguration.MessageHandlers.Add(new DbIdentifierHandler()); 

编辑。 你可以看看这个帖子找到一些灵感: How to pass Owin context to a Repo being injected into Api controller