C#-IoC-WebAPI 2上的Autofac依赖项注入

时间:2018-09-20 19:46:16

标签: c# .net dependency-injection autofac

我无法在应用程序中配置Autofac。感谢您的帮助。以下是例外的代码。如果您需要更多详细信息,请不要犹豫。谢谢!

  1. Api Config

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var setings = config.Formatters.JsonFormatter.SerializerSettings;
        setings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        setings.Formatting = Formatting.Indented;
    
        // Web API Cors
        var origin = "https://localhost:44381";
        EnableCorsAttribute cors = new EnableCorsAttribute(origin, "*", "*");
        config.EnableCors(cors);
    
        // DI
        var builder = new ContainerBuilder();
    
        builder.RegisterType<AlertRepository>()
            .As<IAlertRepository>();
        builder.RegisterType<UnitOfWork>()
            .As<IUnitOfWork>();
        builder.RegisterGeneric(typeof(Repository<>))
            .As(typeof(IRepository<>))
            .InstancePerRequest();
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
    
        var container = builder.Build();
        GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    
        // Web API routes
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
    
  2. 工作单元类别

    public class UnitOfWork : IUnitOfWork
    {
            private readonly CRNetContext _context;
    
            public UnitOfWork(CRNetContext context)
            {
                _context = context;
                Alerts = new AlertRepository(_context);
            }
    
            public IAlertRepository Alerts { get; private set; }
    
            public int Complete()
            {
                return _context.SaveChanges();
            }
    
            public void Dispose()
            {
                _context.Dispose();
            }
    }
    
  3. 异常

  

{     “ message”:“发生错误。”,     “ exceptionMessage”:“尝试创建类型为'AlertsController'的控制器时发生错误。请确保该控制器具有无参数的公共构造函数。”,     “ exceptionType”:“ System.InvalidOperationException”,     “ stackTrace”:“在System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage请求,HttpControllerDescriptor controllerDescriptor,类型controllerType)\ r \ n在System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage请求)\ r \ n位于System.Web.Http.Dispatcher.HttpControllerDispatcher.d__15.MoveNext()“,     “ innerException”:{       “ message”:“发生错误。”,       “ exceptionMessage”:“在激活特定注册时发生错误。有关详细信息,请参见内部异常。注册:Activator = AlertsController(ReflectionActivator),Services = [CRNET.API.Controllers.AlertsController],Lifetime = Autofac.Core。 Lifetime.CurrentScopeLifetime,共享=无,所有权= OwnedByLifetimeScope --->激活特定注册期间发生错误。有关详细信息,请参见内部异常。注册:Activator = UnitOfWork(ReflectionActivator),服务= [CRNET.DAL.Persistance [.IUnitOfWork],生命周期= Autofac.Core.Lifetime.MatchingScopeLifetime,共享=共享,所有权= OwnedByLifetimeScope --->在“ CRNET.DAL.Persistance”类型上都找不到“ Autofac.Core.Activators.Reflection.DefaultConstructorFinder”的构造函数可以使用可用的服务和参数来调用.UnitOfWork':\ r \ n无法解析构造函数'Void .ctor(CRNET.DAL.Models.CRNet的参数'CRNET.DAL.Models.CRNetContext上下文'上下文”)。 (有关详细信息,请参阅内部异常。)(有关详细信息,请参阅内部异常。)”,       “ exceptionType”:“ Autofac.Core.DependencyResolutionException”,       “ stackTrace”:“在Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable 1 parameters)\r\n at Autofac.Core.Resolving.InstanceLookup.Execute()\r\n at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable 1参数)\ r \ n在Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration注册,IEnumerable 1 parameters)\r\n at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable 1参数)\ r \ n(位于Autofac.ResolutionExtensions.TryResolveService(IComponentContext上下文,服务服务,IEnumerable 1 parameters, Object& instance)\r\n at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable 1个参数)\ r \ n,位于Autofac.ResolutionExtensions.ResolveOptional(IComponentContext上下文,类型为serviceType)\ r \ n C:\ projects \ autofac-webapi \ src \ Autofac.Integration.WebApi \ AutofacWebApiDependencyScope.cs:System.Web.Http.Dispatcher上的第76行\ r \ n中的Autofac.Integration.WebApi.AutofacWebApiDependencyScope.GetService(Type serviceType) DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage请求,类型controllerType,Func 1& activator)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)", "innerException": { "message": "An error has occurred.", "exceptionMessage": "An error occurred during the activation of a particular registration. See the inner exception for details. Registration: Activator = UnitOfWork (ReflectionActivator), Services = [CRNET.DAL.Persistance.IUnitOfWork], Lifetime = Autofac.Core.Lifetime.MatchingScopeLifetime, Sharing = Shared, Ownership = OwnedByLifetimeScope ---> None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'CRNET.DAL.Persistance.UnitOfWork' can be invoked with the available services and parameters:\r\nCannot resolve parameter 'CRNET.DAL.Models.CRNetContext context' of constructor 'Void .ctor(CRNET.DAL.Models.CRNetContext)'. (See inner exception for details.)", "exceptionType": "Autofac.Core.DependencyResolutionException", "stackTrace": " at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable 1个参数)\ r \ n在Autofac.Core.Resolving.InstanceLookup.b__5_0()\ r \ n在Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare( Guid id,Func 1 creator)\r\n at Autofac.Core.Resolving.InstanceLookup.Execute()\r\n at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable 1个参数)\ r \ n(位于Autofac.Core.Resolving.Instanc) eLookup.ResolveComponent(IComponentRegistration注册,IEnumerable 1 parameters)\r\n at Autofac.Core.Activators.Reflection.AutowiringParameter.<>c__DisplayClass0_0.<CanSupplyValue>b__0()\r\n at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate()\r\n at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable 1个参数)\ r \ n在Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable 1 parameters)", "innerException": { "message": "An error has occurred.", "exceptionMessage": "None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'CRNET.DAL.Persistance.UnitOfWork' can be invoked with the available services and parameters:\r\nCannot resolve parameter 'CRNET.DAL.Models.CRNetContext context' of constructor 'Void .ctor(CRNET.DAL.Models.CRNetContext)'.", "exceptionType": "Autofac.Core.DependencyResolutionException", "stackTrace": " at Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext context, IEnumerable 1个参数)\ r \ n在Autofac.Core.Activators .Reflection.ReflectionActivator.ActivateInstance(IComponentContext上下文,IEnumerable 1 parameters)\r\n at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable 1个参数)”         }       }     }   }

1 个答案:

答案 0 :(得分:1)

  

无法解析参数'CRNET.DAL.Models.CRNetContext上下文'...

您永远不会在Autofac中注册类型CRNetContext。要修复它,请添加:

builder.RegisterType<CRNET.DAL.Models.CRNetContext>().AsSelf();