WebApi2 응용 프로그램에 UNITY를 구현하려고합니다. 문제는 리소스의 URL에있는 식별자에 따라 기존 SqlConnection을 사용하고 있다는 것입니다. 그래서 uri에 제공된 식별자를 사용하여 내 컨텍스트를 만듭니다. 요청 URI에서 {dbIdentifier}를 가져 와서 MyRepo의 생성자로 구문 분석 할 수 있습니까?Web Api OWIN Unity와의 호스트
USI는 모양을 요청 :/API, 그것은 연주는 처음 {dbIdentifier}/{컨트롤러}/{ID}
구조는 아래와 같다 ... Btw는
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와 함께라면 내 무지를 감수하십시오.
내 코드의업데이트] 유니티 부분 (https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection에서 촬영)
UnityResolver :
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);
}