标签: simple-injector

如何使用Simple Injector注册AutoMapper 4.2.0

已更新至AutoMapper 4.2.0,并按照此处提供的迁移指南进行操作:https://github.com/AutoMapper/AutoMapper/wiki/Migrating-from-static-API/f4784dac61b91a0df130e252c91a0efd76ff51de#preserving-static-feel.尝试将StructureMap的页面上的代码转换为Simple Injector.有人能告诉我这个代码在Simple Injector中的样子吗?

StructureMap

public class AutoMapperRegistry : Registry
{
    public AutoMapperRegistry()
    {
        var profiles =
            from t in typeof (AutoMapperRegistry).Assembly.GetTypes()
            where typeof (Profile).IsAssignableFrom(t)
            select (Profile)Activator.CreateInstance(t);

        var config = new MapperConfiguration(cfg =>
        {
            foreach (var profile in profiles)
            {
                cfg.AddProfile(profile);
            }
        });

        For<MapperConfiguration>().Use(config);
        For<IMapper>().Use(ctx => ctx.GetInstance<MapperConfiguration>().CreateMapper(ctx.GetInstance));
    }
}
Run Code Online (Sandbox Code Playgroud)

简单的注射器

?
Run Code Online (Sandbox Code Playgroud)

c# automapper simple-injector

9
推荐指数
2
解决办法
3952
查看次数

Serilog的ILogger使用Log.ForContext <T>注入,其中T是消费者

Serilog允许创建一个上下文感知记录器:

Log.ForContext<T>()

我想用SimpleInjector注册Serilog,这T是消费者的类型,即它注入的是哪个类.

例如

public class Car
{
    public Car(ILogger logger) <= would be injected using Log.ForContext<Car>()
    {             
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以看到这已经完成了AutoFac.

通过SimpleInjector文档,有一个非常有希望的重载RegisterConditional()(使用Func<TypeFactoryContext, Type>参数).

c.RegisterConditional(typeof (ILogger),
    x => Log.ForContext(x.Consumer.ImplementationType), <= won't compile as expecting a Type
    Lifestyle.Scoped,
    x => true);
Run Code Online (Sandbox Code Playgroud)

但是,我不想告诉SimpleInjector 要构建哪个 Type,而是如何构建一个.

c# simple-injector serilog

9
推荐指数
1
解决办法
5370
查看次数

如何配置Simple Injector以在ASP.NET MVC中运行后台线程

我正在使用Simple Injector来管理我注入的依赖项的生命周期(在这种情况下UnitOfWork),我很高兴有一个单独的装饰器而不是我的服务或命令处理程序,在编写业务逻辑时保存和处理使代码更容易图层(我遵循本博文中概述的架构).

通过在构造根容器的构造过程中使用Simple Injector MVC NuGet包和以下代码,上面的工作完美(并且非常容易),如果图中存在多个依赖项,则相同实例将全部注入 - 完美的实体框架模型上下文.

private static void InitializeContainer(Container container)
{
    container.RegisterPerWebRequest<IUnitOfWork, UnitOfWork>();
    // register all other interfaces with:
    // container.Register<Interface, Implementation>();
}
Run Code Online (Sandbox Code Playgroud)

我现在需要运行一些后台线程并从Simple Injector 文档中了解可以代理命令的线程,如下所示:

public sealed class TransactionCommandHandlerDecorator<TCommand>
    : ICommandHandler<TCommand>
{
    private readonly ICommandHandler<TCommand> handlerToCall;
    private readonly IUnitOfWork unitOfWork;

    public TransactionCommandHandlerDecorator(
        IUnitOfWork unitOfWork, 
        ICommandHandler<TCommand> decorated)
    {
        this.handlerToCall = decorated;
        this.unitOfWork = unitOfWork;
    }

    public void Handle(TCommand command)
    {
         this.handlerToCall.Handle(command);
         unitOfWork.Save();
    }
}
Run Code Online (Sandbox Code Playgroud)

ThreadedCommandHandlerProxy:

public class ThreadedCommandHandlerProxy<TCommand>
    : ICommandHandler<TCommand> …
Run Code Online (Sandbox Code Playgroud)

.net c# dependency-injection asp.net-mvc-3 simple-injector

8
推荐指数
2
解决办法
4419
查看次数

使用Simple Injector使用不同的配置

我正在使用Simple Injector依赖注入框架,它看起来很酷很好.但在构建配置并使用它之后,现在我想知道如何从一种配置更改为另一种配置.

场景:让我们想象一下我在Global Asax中设置了一个配置,我在Container那里有公共和全局实例.现在我想做一些测试,我希望他们使用模拟类,所以我想改变配置.

当然,我可以构建另一个配置并将其分配给Container默认创建的全局,这样每次运行测试时都会设置备用配置.但是在这样做的时候,尽管我处于开发环境中,但Container每个人都会改变,即使是正常的请求.我知道我正在测试这个环境,这应该不重要,但我觉得这不是这样做的方式......我想知道如何以正确的方式从一种配置转换到另一种配置.

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

8
推荐指数
1
解决办法
2707
查看次数

通过SimpleInjector注册单例并返回相同的实例,用于它实现的不同接口

想象一下,我有以下内容:

public interface IocInterface1 { }

public interface IocInterface2 { }

public class IocImpl : IocInterface1, IocInterface2 { }
Run Code Online (Sandbox Code Playgroud)

我想如果我尝试通过IoC获取上述类/接口的任何实例,我得到完全相同的实例,而不是每个类型一个单例.例如,b1b2以下应该是真实的:

_container.RegisterSingle<IocInterface1, IocImpl>();
_container.RegisterSingle<IocInterface2, IocImpl>();
_container.RegisterSingle<IocImpl, IocImpl>();

var test1 = _container.GetInstance<IocInterface1>();
var test2 = _container.GetInstance<IocInterface2>();
var test3 = _container.GetInstance<IocImpl>();

bool b1 = test1 == test2;
bool b2 = test2 == test3;
Run Code Online (Sandbox Code Playgroud)

这可能吗?

c# dependency-injection ioc-container inversion-of-control simple-injector

8
推荐指数
1
解决办法
2450
查看次数

Simple Injector:如何注入HttpContext?

我已经开始使用Simple Injector作为我的DI容器(主要是出于性能原因:如果有人有建议,请告诉我),但我编写的一些类使用HttpContextBase作为构造函数参数.我现在已经解决了从构造函数中删除它并创建一个Property,如下所示:

    public HttpContextBase HttpContext
    {
        get
        {
            if (null == _httpContext)
                _httpContext = new HttpContextWrapper(System.Web.HttpContext.Current);
            return _httpContext;
        }
        set
        {
            _httpContext = value;
        }
    }
Run Code Online (Sandbox Code Playgroud)

但我不喜欢这个解决方案...任何建议?

.net dependency-injection httpcontext simple-injector

8
推荐指数
1
解决办法
5047
查看次数

使用Simple Injector注入控制台应用程序

我使用Simple Injector进行测试,但是在OOP上使用了新的.我正在努力创造松散的夫妻班.这是我的情景.

我有这样的用户回购和界面.

public  class UserRepository:IUserRepository
{
    public void Add(Model.User user)
    {
        Console.WriteLine("Name:"+user.Name+"\n"+"SurName:"+user.SureName);
    }

    public void Delete(int id)
    {
        throw new NotImplementedException();
    }
}

public  interface IUserRepository
{
    void Add(User user);
    void Delete(int id);
}
Run Code Online (Sandbox Code Playgroud)

我的TestInjectedClass类和界面就像我计划在Programe Main中使用的那样.

public class TestInjectedClass:ITestInjectedClass
{
    private readonly IUserRepository _userRepository;
    public  TestInjectedClass(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public void UserRepoRun()
    {
        var user = new User() {Id = 1,Name = "ada",SureName = "stack"};
        _userRepository.Add(user);
    }
}
public interface ITestInjectedClass
{
    void UserRepoRun(); …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection simple-injector

8
推荐指数
2
解决办法
2万
查看次数

如何使用Simple Injector装饰ASP.NET MVC控制器

我想对我的MVC控制器应用一些横切关注点.目前,这是通过抽象基类实现的,但是当我们重构更多代码库以利用依赖注入时,我想知道这是否是Simple Injector可以帮助我通过它的装饰或拦截设施.

所以我试图创建一个非常基本的装饰器:

public class ControllerDecorator : IController
{
    private readonly IController _controller;

    public ControllerDecorator(IController controller)
    {
        _controller = controller;
    }

    public void Execute(RequestContext requestContext)
    {
        // Do something of a cross-cutting nature here...

        _controller.Execute(requestContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的作文根: container.RegisterDecorator<IController, ControllerDecorator>()

但是,我的装饰器Execute方法中的代码似乎永远不会被调用.是因为MVC框架直接解析我的控制器类而不是通过IController?在那种情况下,我该怎么办?我在这里错过了什么?

asp.net-mvc simple-injector

8
推荐指数
1
解决办法
2286
查看次数

使用Simple Injector和IHttpControllerActivator解决ASP.NET Web API中的依赖项

我目前正在使用Simple Injector来解析我的Asp.Net Web Api项目中的依赖项.

从文档中您可以像这样配置它:

protected void Application_Start() {
    // Create the container as usual.
    var container = new Container();
    container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

    // Register your types, for instance using the scoped lifestyle:
    container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);

    // This is an extension method from the integration package.
    container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

    container.Verify();

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

    // Here your usual Web API configuration stuff.
}
Run Code Online (Sandbox Code Playgroud)

这里的要点是注册Web Api控制器并设置自定义依赖项解析器.

但是,我刚刚阅读了Mark Seemann关于如何在Asp.Net Web Api中配置依赖注入的这些文章:

从这些文章中,我了解到有一个比IDependencyResolver解决Web Api依赖关系更好的选择.另一个选择是创建一个实现, …

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

8
推荐指数
1
解决办法
3453
查看次数

IMediatR - 用于通用请求的通用请求处理程序

我目前面临 IMediatR IRequestHandlers 和 IRequest 的问题。为了提供一些背景信息,在我们的工具上,用户可以通过填写几个字段来请求访问该工具。目前,我们有两个级别的访问权限,这意味着我们应该有两个 IRequestHandler,每个 IRequestHandler 一个。由于我们要做的只是将访问请求注册到数据库并发送电子邮件,因此我认为可以创建一个通用的 IRequestHandler 来处理这些情况(如果我们创建移动访问级别,它将在将来有所帮助)。

我对如何通用注入这些类型的处理程序进行了一些研究,但我只能找到非通用注入。我想知道是否有一种方法可以为我在下面介绍的那些 IRequest 注入这些类型的通用 IRequestHandler?

这是我为 IRequest 创建的代码。

public class CreateAccessRequest<TViewModel> : IRequest<OperationResult<long>>, IValidatable
    where TViewModel : AccessRequestViewModel
{
    public TViewModel Request { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是请求处理程序,我可以创建的更通用的处理程序。

public class CreateAccessRequestHandler<TViewModel, TNotificationModel, TEntity> : IRequestHandler<CreateAccessRequest<TViewModel>, OperationResult<long>>
    where TViewModel : AccessRequestViewModel
    where TEntity : Entity
    where TNotificationModel : INotification
{
    private readonly IRepository<TEntity> _accessRequestRepository;
    private readonly IMediator _mediator;
    private readonly IMapper _mapper;

    public CreateAccessRequestHandler(IRepository<TEntity> accessRequestRepository, IMediator mediator, IMapper mapper)
    {
       // …
Run Code Online (Sandbox Code Playgroud)

.net generics simple-injector mediatr asp.net-core

8
推荐指数
1
解决办法
9019
查看次数