标签: simple-injector

如何使用Simple Injector模拟模块/安装程序/注册表

Autofac有模块,Windsor有安装程序和StructureMap注册表...使用Simple Injector如何将配置逻辑打包成可重用的类?

我试过了:

public interface IModule { }

public class FooModule : IModule
{
    public FooModule(SimpleInjector.Container container)
    {
        container.RegisterSingleton<IBar, Bar>();
        container.RegisterSingleton<IFoo, Foo>();
    }
}
Run Code Online (Sandbox Code Playgroud)

我在Composition Root中使用它:

public static void Main(string[] args)
{
    var container = new SimpleInjector.Container();
    container.RegisterCollection<IModule>(new FooModule(container));
    ...
}
Run Code Online (Sandbox Code Playgroud)

但是,FooModule取决于容器,可能不是一个好的做法...请参阅http://code.google.com/p/autofac/wiki/BestPractices:

如果组件依赖于容器,请查看它们如何使用容器来检索服务,并将这些服务添加到组件(依赖注入)构造函数参数中.

.net c# dependency-injection ioc-container simple-injector

13
推荐指数
1
解决办法
3854
查看次数

在Quartz.Net的IJobFactory接口中,ReturnJob的目的是什么

我使用simpleInjector作为IOC容器bue我没有清楚地看到ReturnJob的责任是什么,我想知道如何进行?

这是我到目前为止所做的代码:

public class SimpleInjectorJobFactory:IJobFactory
    {
        private readonly Container _container;
        public SimpleInjectorJobFactory()
        {
            _container= new Container();
        }

        public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
        {
            return _container.GetInstance(bundle.JobDetail.JobType) as IJob;
        }

        public void ReturnJob(IJob job)
        {
            throw new System.NotImplementedException();
        }
    }
Run Code Online (Sandbox Code Playgroud)

c# quartz-scheduler quartz.net simple-injector

12
推荐指数
1
解决办法
3594
查看次数

在Simple Injector中注册具有多个构造函数和字符串依赖关系的类型

我正在试图弄清楚如何使用Simple Injector,我已经在项目周围使用它,没有注册简单服务及其组件的问题.

但是,我希望在具有两个以上实现接口的构造函数的组件时使用依赖注入器.

public DAL: IDAL
{
    private Logger logger;
    string _dbInstance;
    public DAL()
    {
        logger = new Logger();
    }

    public DAL(string databaseInstance)
    {
         logger = new Logger();
         _dbInstance = databaseInstance;
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我注册服务的方式:

container.Register<IDAL, DAL>();
Run Code Online (Sandbox Code Playgroud)

运行代码,这是发生的错误:

要使容器能够创建DAL,它应该只包含一个公共构造函数,但它有2个.

删除构造函数后,下一个错误是它不允许我的构造函数接受参数.

DAL类型的构造函数包含String类型的参数'databaseInstance',它不能用于构造函数注入.

有什么方法我可以在类有2个以上的公共构造函数的情况下进行依赖注入吗?或者有一个接受参数的公共构造函数?

我在这里阅读文档:SimpleInjector(入门)

该文档开始易于理解,但它会呈指数级复杂,如果他们提到的后一个例子中的任何一个与我的问题有关,我就很难解读.

c# dependency-injection inversion-of-control constructor-injection simple-injector

12
推荐指数
1
解决办法
1万
查看次数

如何使用WebAPI,WCF,SignalR和后台任务在MVC Web应用程序中配置简单的注入器容器和lifestylse

简单的注入器文档提供了有关如何为WebRequest,Web API,WCF设置容器的很好示例......但这些示例一次特定于一种技术/生活方式.我们的Web应用程序大部分使用它们!我不清楚如何配置容器以适应多种生活方式.


假设我有一个带有Web API的MVC项目.我有以下对象:

  • MyDbContext:我的实体代码第一个db上下文
  • 由MyDataProvider实现的IMyDataProvider:包含查询逻辑并使用MyDbContext
  • MyController:使用IMyDataProvider的MVC控制器
  • MyApiController:使用IMyDataProvider的WebApi控制器

我应该为每种生活方式创建和配置一个容器吗?

当我注册的所有内容RegisterPerWebRequest<T>都适用于两种类型的控制器.这样安全吗?或者在Web API控制器中使用async/await时会遇到麻烦吗?

当我同时注入相同实例的MVC和Web API控制器时,最佳配置是什么?

我应该使用混合生活方式吗?


现在让事情变得复杂......我们的应用程序也使用后台任务和SignalR.

这些都有时会发生在WebRequest之外,并且需要访问如上所述的相同对象.

最好的解决方案是使用Lifetime范围?

我需要为这种生活方式创造一个新的容器吗?或者我可以重用/重新配置我的MVC/Web API容器吗?

有三重生活方式吗?

c# dependency-injection simple-injector

12
推荐指数
2
解决办法
3972
查看次数

使用Simple Injector注册IAuthenticationManager

我正在为Simple Injector配置设置,我已将所有注册移动到OWIN管道.

现在问题是我有一个控制器AccountController,实际上参数为

public AccountController(
    AngularAppUserManager userManager, 
    AngularAppSignInManager signinManager, 
    IAuthenticationManager authenticationManager)
{
    this._userManager = userManager;
    this._signInManager = signinManager;
    this._authenticationManager = authenticationManager;
}
Run Code Online (Sandbox Code Playgroud)

现在我的Owin Pipeline配置看起来像这样

public void Configure(IAppBuilder app)
{
    _container = new Container();
    ConfigureOwinSecurity(app);
    ConfigureWebApi(app);
    ConfigureSimpleinjector(_container);

    app.Use(async (context, next) =>
    {
        _container.Register<IOwinContext>(() => context);
        await next();
    });

    _container.Register<IAuthenticationManager>(
        () => _container.GetInstance<IOwinContext>().Authentication);

    _container.Register<SignInManager<Users, Guid>, AngularAppSignInManager>();
}

private static void ConfigureOwinSecurity(IAppBuilder app)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        CookieName = "AppNgCookie",
        //LoginPath = new PathString("/Account/Login")
    });
}

private static …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc simple-injector asp.net-identity asp.net-identity-2

12
推荐指数
2
解决办法
6335
查看次数

使用Simple Injector注册NLog ILogger

有什么方法可以获得上下文所以我可以检索loggerName并使用LogManager.GetLogger(loggerName)而不是LogManager.GetCurrentClassLogger()

我注意到container.RegisterConditional()可以访问上下文.

另外,我现在想避免像SimpleLogging.NLog这样的解决方案.

最后,我愿意接受这不是正确的方法.顺便说一下,AOP是我已经探索过的一个选项(将记录器作为单身人员是一种很好的做法吗?).

注意:我知道GetCurrentClassLogger()获取与.NET反射检索的相同信息.

using NLog;
using SimpleInjector;

namespace DependencyInjection
{
    class Program
    {
        private static Container _container;
        static void Main(string[] args)
        {
            Bootstrap();
            _container.GetInstance<Greeter>().Greet();
        }

        private static void Bootstrap()
        {
            _container = new Container();

            _container.Register<ILogger>(() => LogManager.GetCurrentClassLogger(), Lifestyle.Transient);
            _container.Register<Greeter>();

            _container.Verify();
        }

        public class Greeter
        {
            private ILogger _logger;

            public Greeter(ILogger logger)
            {
                _logger = logger;
            }

            public void Greet()
            {
                _logger.Log(LogLevel.Info, "Hello world!");
            } …
Run Code Online (Sandbox Code Playgroud)

.net dependency-injection nlog ioc-container simple-injector

12
推荐指数
1
解决办法
5882
查看次数

简单注入器:使用ILoggerFactory.CreateLogger注册ILogger <T> <T>()

我正在使用一个利用Simple Injector作为依赖注入器的项目.另一方面,该项目使用Microsoft.Extensions.Logging来记录某些类中发生的事件.

我的技术问题很容易解释.我想在我的DI中注册ILogger独立于正在调用的类T,但我需要从我的ILoggerFactory.CreateLogger<T>()方法中执行它,因为这将使用记录器配置Microsoft.Extensions.Configuration.

我需要使用这样的东西来实例我的记录器:

private Microsoft.Extensions.Logging.ILogger CreateLogger<T>()
{
     var factory = this.ResolveService<ILoggerFactory>();
     var logger = factory.CreateLogger<T>();
     return logger;
}
Run Code Online (Sandbox Code Playgroud)

我可以通过以下方式实现注射:

Container.Register(typeof(ILogger<>), typeof(Logger<>));
Run Code Online (Sandbox Code Playgroud)

这使我们可以解决类似的问题:

public class SomeApiController : ApiController
{
     public SomeApiController(ILogger<SomeApiController> logger)
     {
         //logger is well instantiated, but doesn't got the configuration
         logger.LogInformation("test log.");
     }
}
Run Code Online (Sandbox Code Playgroud)

但正如我所说,这样做不会通过从Microsoft.Extensions.Logging.ILoggerFactory类中获得的配置,所以这没用.

有没有办法ILogger<T>使用我的注册CreateLogger<T>

c# dependency-injection simple-injector ms-extensions-logging

12
推荐指数
2
解决办法
5291
查看次数

使用单个接口注册多个实现

有没有办法注册单个接口,该接口由多个具体类使用[simple-injector]并且不使用模板接口实现?

说我们有2班MyClass1,并Myclass2与这两个类都实现IInterface1

现在使用[simple-injector]我们无法做到这一点

container.Register<IInterface1, Myclass1>();
container.Register<IInterface1, Myclass2>();
Run Code Online (Sandbox Code Playgroud)

将现有接口转换为模板接口对现有代码库来说是一项艰巨的任务.希望有一些更容易的.

c# dependency-injection c#-4.0 simple-injector

11
推荐指数
1
解决办法
1万
查看次数

如何使用简单的注入器,存储库和上下文 - 代码优先

我正在尝试使用Simple Injector来创建我的存储库并在业务逻辑层中使用它(我也想使用PerWebRequest方法).

在DAL层我有:

public interface IRepository<T> where T : class
{
    void Add(T entity);
    void Delete(T entity);
    void Delete(int id);
    void Update(T entity);
    T GetById(int Id);
    IQueryable<T> All();
    IEnumerable<T> Find(Func<T, bool> predicate);
}
Run Code Online (Sandbox Code Playgroud)

并且:

public class EFRepository<T> : IRepository<T>, IDisposable where T : class
{
    #region Members
    protected DbContext Context { get; set; }
    protected DbSet<T> DbSet { get; set; }
    #endregion

    #region Constructors

    public EFRepository(DbContext dbContext)
    {
        if (dbContext == null)
            throw new ArgumentNullException("dbContext");
        Context = dbContext;
        DbSet = …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc repository inversion-of-control simple-injector

11
推荐指数
1
解决办法
9636
查看次数

Simple Injector:需要创建具有依赖项的类的工厂类

我有一个工厂类,可以创建几种不同类型的类.工厂已在集装箱中注册.在工厂内部创建类的建议方法是什么,因为它们也有依赖项.我显然希望避免对容器的依赖,但如果我新建这些类,那么他们将不会使用容器.例如

public class MyFactory
{
    public IMyWorker CreateInstance(WorkerType workerType)
    {
        if (workerType == WorkerType.A)
              return new WorkerA(dependency1, dependency2);

        return new WorkerB(dependency1);

    }
}
Run Code Online (Sandbox Code Playgroud)

所以问题是我从哪里获取这些依赖项.

一种选择可能是使它们成为工厂的依赖关系.例如

public class MyFactory
{
    private Dependency1 dependency1;
    private Dependency2 dependency2;

    public MyFactory(Dependency1 dependency1, Dependency2, dependency2)
    {
        this.dependency1 = dependency1; this.dependency2 = dependency2;
    }

    public IMyWorker CreateInstance(WorkerType workerType)
    {
        if (workerType == WorkerType.A)
              return new WorkerA(dependency1, dependency2);

        return new WorkerB(dependency1);

    }
}
Run Code Online (Sandbox Code Playgroud)

另一个可能是注册工人类型并制造工厂的依赖关系,例如

public class MyFactory
{
    private IWorkerA workerA;
    private IWorkerB workerB;

    public MyFactory(IWorkerA workerA, …
Run Code Online (Sandbox Code Playgroud)

.net c# dependency-injection ioc-container simple-injector

10
推荐指数
2
解决办法
3894
查看次数