Я следил за этой статьей:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection#dependency-scope-and-controller-lifetime
Я получаю ошибку в названии:
Убедитесь, что контроллер имеетоткрытый конструктор без параметров.
В основном код Unity такой же, как в проекте от Microsoft.
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var container = new UnityContainer();
container.RegisterType<ITrace, Trace>(new HierarchicalLifetimeManager());
container.RegisterType<IUtility, Utility>(new HierarchicalLifetimeManager());
container.RegisterType<IValidator, Validator>(new HierarchicalLifetimeManager());
container.RegisterType<IDeliveryService, DeliveryService>(new HierarchicalLifetimeManager());
container.RegisterType<ISaleService, SaleService>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
У меня есть UnityResolver:
public class UnityResolver : IDependencyResolver
{
protected IUnityContainer container;
public UnityResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
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 (ResolutionFailedException)
{
return new List<object>();
}
}
public IDependencyScope BeginScope()
{
var child = container.CreateChildContainer();
return new UnityResolver(child);
}
public void Dispose()
{
container.Dispose();
}
Unityследует создать экземпляры контроллеров, использующих это. Моя единственная забота - это контекст БД. Я пытался найти способы регистрации, но ничего не получил.
Как меня просили, вот мой dbcontext:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false)
{
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
Configuration.ValidateOnSaveEnabled = false;
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
Я впервые использую Unity.