小编Ste*_*ven的帖子

如何使用简单的注入器将其接口注册为单例类型?

我有以下模型:

public interface IUserLookupService {
    Guid[] GetDirectChilds(Guid userId);
    Guid[] GetAllChilds(Guid userId);
    Guid GetDepartment(Guid userId);
}

public interface ICanRefreshCache{
    void Refresh();
}

public class XHandler : IEventHandler<UserNameChanged> { ... }
public class YHandler : IEventHandler<TeamCreated> { ... }

public class CachedUserLookupService
    : IUserLookupService,
    ICanRefreshCache,
    IEventHandler<UserNameChanged>
{
    private Func<ISession> _sessionFactory;
    private IDictionary<Guid, UserInfo> _users = new Dictionary<Guid, UserInfo>();

    public CachedUserLookupService(Func<ISession> sessionFactory) {
        _sessionFactory = sessionFactory;
    }

    public void Handle(UserNameChanged ev) {
        // change cache with new event parameters
    }

    public void Refresh() …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection simple-injector

3
推荐指数
1
解决办法
1554
查看次数

简单的注入器标识UserManager <AppUser,Int32>注册错误

我正在关注Onion Architecture并使用Identity Framework.在我的核心项目中,我有:

public interface IUserRepository : IDisposable
{
     // Repository methods.......
}
Run Code Online (Sandbox Code Playgroud)

在我的Architecture.Repository中,我有

public class UserRepository : IUserRepository
{
     // This is Identity UserManager
     private readonly UserManager<AppUser, int> _userManager;   
     private readonly IAuthenticationManager _authenticationManager;
     private bool _disposed;

     public UserRepository(UserManager<User, int> userManager,
         IAuthenticationManager authenticationManager)
     {
          _userManager = userManager;
          _authenticationManager = authenticationManager;
     }
}
Run Code Online (Sandbox Code Playgroud)

在我的依赖解析项目中,我有:

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(IocConfig),
    "RegisterDependencies")]
namespace AdShad.Infrastructure.DependencyResolution
{
    public class IocConfig
    {
        public static void RegisterDependencies()
        {
            var container = new Container();
            container.RegisterWebApiRequest<IUnitOfWork, UnitOfWork>();
            container.RegisterWebApiRequest<IUserRepository, UserRepository>();

            container.RegisterManyForOpenGeneric(typeof(IRepository<>),
                typeof(BaseRepository<>).Assembly);
            container.RegisterWebApiRequest<IEntitiesContext, …
Run Code Online (Sandbox Code Playgroud)

c# asp.net dependency-injection simple-injector asp.net-identity

3
推荐指数
1
解决办法
5411
查看次数

在 DI 容器中安全地重新初始化“单实例”依赖项

我在 Web 应用程序中有一个广泛使用的缓存接口,其实现当前注册为SingleInstance.

当前的缓存实现假定单线程初始化,但一旦初始化是不可变的,因此可以在多个线程之间安全地共享。

但是,这意味着当前,如果基础值发生更改,则缓存不会更新,直到应用程序重新启动。虽然更新底层值很少见,但我们现在希望提供修改底层值的应用程序行为,然后告诉缓存刷新。

我可以修改缓存实现以使用锁定,或者可能利用 .NET 并发集合之一来安全地更新缓存值。

但是,我想知道 autofac 是否提供了一种功能,允许我在下一个请求中为新实例更改已注册的实例,以便不需要修改缓存实现本身。

所以理想的行为是,当我们修改底层值时,我们会触发一个新缓存实例的创建。一旦实例完成初始化,所有正在进行的请求将继续使用旧的缓存实例,任何新的 http 请求范围解析为更新的实例。

autofac 是否提供内置方式来支持这种情况?

dependency-injection autofac

3
推荐指数
1
解决办法
2889
查看次数

使用IoC注册通用UnitOfWork <>时出错

我在我的应用程序中为我的DbContexts提供了一个通用的UnitOfWork实现,其工作原理如下:

 public class UnitOfWork<TContext> : IDisposable, IUnitOfWork<TContext>
        where TContext : DbContext
 {
     private readonly TContext _context;

     [..UoW default implementations..]

     public void Dispose()
     {
        _context.Dispose();
     }
  }
Run Code Online (Sandbox Code Playgroud)

注册......:

public static class SimpleInjectorWebApiInitializer
    {
        /// <summary>Initialize the container and register it as Web API Dependency Resolver.</summary>
        public static void Initialize()
        {
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

            InitializeContainer(container);

            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

            container.Verify();

            GlobalConfiguration.Configuration.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);
        }

        private static void InitializeContainer(Container container)
        {

            // For instance:
            container.Register(typeof(IUnitOfWork<>), typeof(UnitOfWork<>), Lifestyle.Scoped);
            container.RegisterWebApiRequest<IBankRepository, BankRepository>(); …
Run Code Online (Sandbox Code Playgroud)

c# ioc-container inversion-of-control simple-injector asp.net-web-api

3
推荐指数
1
解决办法
1854
查看次数

如何配置Ninject以注入NodaTime IClock

在我的NinjectConfigurator中

container.Bind<IClock>().To<SystemClock>(); 
Run Code Online (Sandbox Code Playgroud)

我也试过了

container.Bind<IClock>().To<SystemClock>().InSingletonScope();
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

错误激活IClock使用结合IClock到SystemClock 没有构造函数可用来创建实现类型的实例.

激活路径:3)将依赖IClock注入SystemManager类型构造函数的参数时钟2)将依赖ISystemManager注入到AccountController类型构造函数的参数systemManager中1)对AccountController的请求

建议:1)确保实现类型具有公共构造函数.2)如果已实现Singleton模式,请使用与InSingletonScope()的绑定.

这是我的注入类,与我在项目中使用IoC的所有其他工作类相同:

private readonly IDateTime _dateTime;
private readonly IClock _clock;

public SystemManager(IDateTime dateTime, IClock clock)
{
    this._dateTime = dateTime;
    this._clock = clock;
}
Run Code Online (Sandbox Code Playgroud)

我找不到任何可以帮助我的事情.任何帮助深表感谢.

c# ninject nodatime

3
推荐指数
1
解决办法
694
查看次数

SimpleInjector:具有多个接口的类的批量注册

假设我有以下实现以下接口的类:

class MyClassA : IInterface<MyClassA>, IInterface
class MyClassB : IInterface<MyClassB>, IInterface
Run Code Online (Sandbox Code Playgroud)

我还有另外两个类似的类:

class ImportA {
    public ImportA(IEnumerable<IInterface>) {}
}

class ImportB {
    public ImportB(IInterface<MyClassA>) {}
}
Run Code Online (Sandbox Code Playgroud)
  • 我希望ImportA随IInterface我的程序集中实现的每个类一起注入。
  • 我希望ImportB仅注入的一个实例IInterface<MyClassA>。
  • 我希望来自这两种方法的具体类MyClassA的实例相同(生命周期:单例)。

我不知道如何使它与Simple Injector一起使用。我已经尝试过RegisterCollection并https://simpleinjector.readthedocs.org/en/latest/howto.html#register-multiple-interfaces-with-the-same-implementation

我最接近的错误是说一个类作为Singleton导入而另一个作为Transient导入。

我尝试将所有LifeStyles更改为Singleton,并将配置默认设置为Singleton,但无济于事。

更新1: 我正在寻找一种自动化的方法。我有很多课程要注册,不想手工做。这是一个不同的示例。以下注册示例无效。自动执行失败的原因是:

An exception of type 'SimpleInjector.ActivationException' occurred in  
SimpleInjector.dll but was not handled in user code

Additional information: The constructor of type MyClassB contains the 
parameter with name 'myClassA' and type IInterface<MyClassA> that is not 
registered. Please ensure IInterface<MyClassA> …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection simple-injector

3
推荐指数
1
解决办法
909
查看次数

简单的Injector,依赖于实现相同接口的两个对象

我正在编写一个应用程序(通过ASP.NET Web API公开),其目的是消耗两个数据源,并揭示相似之处和不同之处.因此API具有以下设置:

public class FooController : WebAPI
{
    public FooController(IFooRepository repoFromSourceA, IFooRepository repoFromSourceB)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

保持哪一个来源(SourceA和SourceB不能互换)的区​​别似乎使得container.RegisterCollection(..)不可能(或非常危险)使用.此外,由于一个类正在消耗两个实现,因此Decorator似乎不合适.

那么,我将如何设置此依赖注入?

c# dependency-injection simple-injector asp.net-web-api

3
推荐指数
1
解决办法
598
查看次数

如何在Simple Injector中为工厂创建的对象解析装饰器

所以这将涉及到我展示了很多我的管道,但我会尽量将它保持在最低限度,以保持这个问题的简单.

我的一个API端点依赖外部提供程序来完成调用.当用户向该端点发送查询时,他们可以指定在处理查询时他们希望我们使用哪个提供商,假设提供商是Bing和Google.

所以我有一个IProvider接口和两个具体的实现BingProvider和GoogleProvider(在我真正的API提供者接口实际上是一个通用的接口,但我离开的仿制药,以避免使这个混乱比它是).我需要根据查询中的字段解析正确的提供程序.Simple Injector不允许注册同一接口的多个具体实现,因此我必须使用工厂; 我创建一个看起来像这样的东西:

public class ProviderFactory
{
    private readonly Func<string, IProvider> _Selector;

    public ProviderFactory(Func<string, IProvider> selector)
    {
        this._Selector = selector;
    }

    public IProvider Get(string provider)
    {
        return this._Selector(provider);
    }
}
Run Code Online (Sandbox Code Playgroud)

我通过这样的方式在容器中注册我的工厂:

container.RegisterSingleton<ProviderFactory>(new ProviderFactory(provider =>
    {
        switch (provider)
        {
            case "Bing":
                return container.GetInstance<BingProvider>()
            case "Google":
                return container.GetInstance<GoogleProvider>()
            default:
                throw new ArgumentOutOfRangeException("Unknown provider: " + provider);
        }
    }));
Run Code Online (Sandbox Code Playgroud)

我测试一下 有用.太棒了.

现在我需要为我创建和注册多个装饰器IProvider.每个具体实现IProvider必须在容器解析它们时应用这些装饰器.为了这个例子,我可以说我有Decorator1和Decorator2哪个实现IProvider …

c# decorator simple-injector

3
推荐指数
1
解决办法
438
查看次数

ASP.NET 5:如何在Microsoft.Extensions.Logging中配置日志路径

我正在开发一个MVC6 Web应用程序,我是ASP.NET 5的新手.我可以看到Logging(Microsoft.Extensions.Logging)在ASP.NET 5中的许多地方(例如:AccountController.cs)使用默认的Web应用程序模板,但我无法弄清楚在何处配置创建的日志文件的路径.以下设置位于appsettings.json文件中.

"Logging": {
"IncludeScopes": false,
"LogLevel": {
  "Default": "Verbose",
  "System": "Information",
  "Microsoft": "Information"
}  }
Run Code Online (Sandbox Code Playgroud)

在本节中添加参数是否足够?如果是,参数名称是什么?如果没有,该怎么办?

以前我使用Log4Net,配置是在logger.config文件中完成的.

asp.net-core-mvc asp.net-core ms-extensions-logging

3
推荐指数
1
解决办法
6100
查看次数

MVC5 Web API 和依赖注入

尝试在没有第三方工具的情况下在 Web API 2 上做一些 DI。
因此,从一些示例中我得到了自定义依赖项解析器(为什么没有集成的?奇怪,甚至Microsoft.Extensions.DependencyInjection都没有提供):

public class DependencyResolver : IDependencyResolver
    {
        protected IServiceProvider _serviceProvider;

        public DependencyResolver(IServiceProvider serviceProvider)
        {
            this._serviceProvider = serviceProvider;
        }

        public IDependencyScope BeginScope()
        {
            return this;
        }

        public void Dispose()
        {

        }

        public object GetService(Type serviceType)
        {
            return this._serviceProvider.GetService(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return this._serviceProvider.GetServices(serviceType);
        }

        public void AddService()
        {

        }
    }
Run Code Online (Sandbox Code Playgroud)

然后创建了这个类:

public class ServiceConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var services = new ServiceCollection();
            services.AddScoped<IMyService, MyServiceClient>();

            var resolver …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection asp.net-web-api asp.net-mvc-5 asp.net-web-api2

3
推荐指数
1
解决办法
3167
查看次数