Transient and Scoped services consuming a singleton data source - c#

I am trying to learn dependency inversion and IOC. In the process, I have hit a wall.
This is what I understand about DI principle -> high-level classes are based on abstractions and not implementations.
All good.
So keeping the above in mind. I have the following example.
public interface IServiceA
{
public void DoSomething();
}
public class ServiceA : IServiceAInterface
{
IDataInterface dataSource;
DataSourceType data;
// omitted config injectino for brevity
public ServiceA(IDataInterface _data)
{
dataSource = _dataSource;
var dataSourceName = config.GetValue<string>("DataSourceName");
data = dataSource.GetDataSource(dataSourceName);
}
public void doSomething()
{
data.doSomething();
}
}
public interface IDataInterface
{
public DataSourceType getDataSource(string ds);
}
public class DataAccessService : IDataInterface
{
public DataSourceType GetDataSource(string dataSource)
{
if (dataSource == "InApp")
{
var source = new DataSourceType();
return source;
}
else
{
return null;
}
}
}
The above is a service class which needs data to perform tasks which it gets from DataAccessService.
Now I am using an application class/model for persistence throughout the app lifetime. Therefore I have registered it as a singleton.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
---
services.AddSingelton<IDataInterface,DataAccessService>();
service.AddScoped<IServieAInterface,ServiceA>();
---
}
This does not work.
I hypothesize it is because, the parent service (service A) has a lesser lifetime than the child service (DataAccessService).
I have understood through this that service A is responsible for instantiation of the object.
However, I expected the IOC container to instantiate only one DataAccessService object and inject it to all services that need this.
Not sure why my assumption is wrong.
Based on the above hypothesis I tried the following:
public interface IDataInterface
{
}
public class DataAccessService : IDataInterface
{
public DataSourceType dataSource;
public DataAccessService(string ds)
{
if (ds == "InApp")
{
this.dataSource = new DataSourceType();
}
else
{
this.dataSource = null;
}
}
}
public class ServiceA: DataAccessService,IServceAInterface
{
DatSourceTye data;
public ServiceA():base("InApp")
{
config = _config;
data = dataSource;
}
public void doSomething()
{
data.doSomething();
}
}
Startup.cs
// Hoping to pass parameter through startup
services.AddSingleton<IDataInterface>(x =>
ActivatorUtilities.CreateInstance<DataAccessService>(x, "InApp")
);
service.AddScoped<IServieAInterface,ServiceA>();
I hoped the above would work, as here the DataAccessService is responsible for initialization.
But still a new DataAccessService object is created for every class.
I think, I have messed up my understanding about how the life times work.
need help on this.
Also, what I am trying to achieve is a singleton data source on which different services act on throughout the application lifetime.
Transient and scoped services consuming a singleton data source. I think this should be possible
Is there something bad in terms of design in what I am trying to achieve?

public DataAccessService(string ds)
{
if (ds == "InApp")
{
this.dataSource = new DataSourceType();
}
else
{
this.dataSource = null;
}
}
This method in the data service was being called every time, I needed the data source.
As this method is instantiating another class manually, though the service is singleton,
every time the above method - DataAccessService was called , I was getting a new instance.

Related

How to resolve scoped service inside singleton object

I have MemoryCache objects (Application,Configuration etc) which I registered them as Singleton. Also there are scoped repositories which selects data from db to fill cache.
For example here is the Singleton registered class,
public class ApplicationCache : MultipleLoadCache<Application>
{
public ApplicationCache()
{
}
}
MultipleLoadCache overrides the CacheItemPolicy, (there is also SingleLoadCache),
public class MultipleLoadCache<TEntity> : SmartCache<TEntity> where TEntity : class
{
public MultipleLoadCache()
{
}
protected override CacheItemPolicy SetPolicy()
{
return new CacheItemPolicy()
{
AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(15)
};
}
}
And base class is,
public class SmartCache<TEntity> : IDisposable where TEntity : class
{
public bool TryGetList(IRepository<TEntity> repository, out List<TEntity> valueList)
{
valueList = null;
lock (cacheLock)
{
GenerateCacheIfNotExists(repository, out valueList);
if (valueList == null || valueList.Count == 0)
{
valueList = (List<TEntity>)_memoryCache.Get(key);
}
}
return valueList != null;
}
I know that scoped services can't be injected to singleton class. So I prefer to use method injection.
private void GenerateCacheIfNotExists(IRepository<TEntity> repository, out List<TEntity> list)
{
list = null;
if (!_memoryCache.Any(x => x.Key == key)) // if key not exists, get db records from repo.
{
IEnumerable<TEntity> tempList = repository.GetList();
list = tempList.ToList();
_cacheItemPolicy = SetPolicy();
SetCacheList(list);
}
}
}
And at controller I try to get cache values, but this part seems wrong to me. If I try to get cache values, I shouldn't pass repository as parameter.
private readonly ApplicationCache _appCache;
public LogController(ApplicationCache appCache)
{
_appCache = appCache;
}
[HttpPost]
[Route("Register")]
public List<Application> Register([FromServices] IApplicationRepository repository)
{
List<Application> cf;
_appCache.TryGetList(repository, out cf);
return cf;
}
Also, by doing Method Injection. I am also unable to use RemovedCallBack event of CacheItemPolicy. Because, when callback triggers (reload cache), I need repository to get records from db again.
Is this design seems nice, what is the best design to do this by using callback events of MemoryCache?
Update 1-
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMemoryCache();
services.AddSingleton(x => new ApplicationCache());
services.AddScoped<IApplicationRepository, ApplicationRepository>();
}
Thanks,
I had the same issue. Since static classes is compiled at the beginning it cannot inject the required services later. I figured it out by using IServiceScopeFactory.
You basically inject IServiceScopeFactory serviceScopeFactory in the constructer .
static SampleClass(IServiceScopeFactory serviceScopeFactory){
//serviceScopedFactory will act as Singleton, since it is a static class
_serviceScopeFactory = serviceScopeFactory;
}
And use it like this in the method :
using (var scope = _serviceScopeFactory.CreateScope())
{
var service = scope.ServiceProvider.GetRequiredService<IService>();
//Here you can use the service. This will be used as Scoped since it will be
//recreated everytime it is called
}

DbContext is Disposed When Using Autofac Dependency Injection on WebApi project

I have a WebApi project using Entity Framework 6.0, Autfac for DI and CQRS architecture. The problem I have that DbContext isn't disposing how it supposed to. The action I take:
I run two quick requests, e.g. send request from Postman to one endpoint, runtime stops on breakpoint in controller method, I send second request to another endpoint in different controller.
Resume Runtime
if the second request finished before the first one is done, the first one throws and error that dbcontext was disposed and it cannot run whatever it was supposed to do
Originally problem appeared when I posted and patched from frontend one after another.
It seems like lifetime scope is not really per-request. It seems like all dbcontexts are disposed on one of the request's end. The other one does not have anything to work with.
How is it configured?
Starting from the highest layer - controller:
public class UsersController : BaseController, IUsersApi
{
private readonly IUserService _userService;
public UsersController(IUserService userService, ILogging logging) : base(logging)
{
_userService = userService;
}
[HttpGet]
[Route("api/users")]
public IList<UserDto> GetUsers()
{
try
{
return _userService.GetAllUsers();
}
catch (Exception e)
{
_logger.Error(e);
_logger.Trace(e);
throw;
}
}
[HttpPatch]
[Route("api/users/")]
public IHttpActionResult EditUsers(ICollection<UserEditDto> model)
{
try
{
_userService.EditUsers(model);
return Ok();
}
catch (Exception e)
{
_logger.Error(e);
_logger.Trace(e);
return BadRequest("Error");
}
}
}
Service layer:
public class UserService : IUserService
{
private readonly IServiceTools _serviceTools;
private readonly IUserQuerier _userQuerier;
public UserService(IServiceTools serviceTools, IUserQuerier userQuerier)
{
_serviceTools = serviceTools;
_userQuerier = userQuerier;
}
public void EditUsers(ICollection<UserEditDto> model)
{
var mapper = _serviceTools.AutoMapperConfiguration.Configure().CreateMapper();
var userEditCommands = mapper.Map<ICollection<UserEditDto>, ICollection<EditUserCommand>>(model);
foreach (var command in userSaveCommands)
{
_serviceTools.CommandBus.SendCommand(command);
CacheHelper.Clear(command.Id.ToString());
}
}
public IList<UserDto> GetAllUsers()
{
var allUsers = _userQuerier.GetAllUsers();
var result = allUsers.Select(x => new UserDto()
{
...
}).ToList();
return result;
}
}
Service Tools interface where command bus sits:
public interface IServiceTools
{
ICommandBus CommandBus { get; }
IAutoMapperConfiguration AutoMapperConfiguration { get; }
IIdentityProvider IdentityProvider { get; }
}
public class ServiceTools : IServiceTools
{
public ServiceTools(ICommandBus commandBus, IAutoMapperConfiguration autoMapperConfiguration, IIdentityProvider identityProvider)
{
CommandBus = commandBus;
AutoMapperConfiguration = autoMapperConfiguration;
IdentityProvider = identityProvider;
}
public ICommandBus CommandBus { get; }
public IAutoMapperConfiguration AutoMapperConfiguration { get; }
public IIdentityProvider IdentityProvider { get; }
}
And whatever handler for command:
public class EditUserHandler : IHandleCommand<EditUserCommand>
{
private readonly ICommandsContext _commandsContext;
public SaveUserHandler(ICommandsContext commandsContext)
{
_commandsContext = commandsContext;
}
public void Handle(EditUserCommand command)
{
... using dbcontext here...
}
}
}
For DI I use Autofac, all resources are set to per-request lifetime, split into modules, e.g. module for data access
public class DataModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AppNameDbContext>().As<ICommandsContext>().InstancePerRequest();
builder.RegisterType<AppNameDbContext>().As<IQueryContext>().InstancePerRequest();
base.Load(builder);
}
}
The difference between both interfaces is that IQueryContext cannot change entity states and use SaveChagnes() method. IQueryContext have all DbSets in it, while ICommandsContext inherits from it and adds SettingState methods (added, modified, deleted) and SaveChanges() method.
IQueryContext is injected into queries and ICommandsContext into commands as seend in example aboove.
Now the Autofac config for command bus looks like that:
public class InfrastractureModule : Module
{
private ICommandsContext _commandsContext;
private ITranslationsCommandsContext _translationsCommandsContext;
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AutoMapperConfiguration>().
As<IAutoMapperConfiguration>().InstancePerRequest();
builder.RegisterType<ServiceTools>().As<IServiceTools>().InstancePerRequest();
builder.Register(c =>
{
_commandsContext = c.Resolve<ICommandsContext>();
_translationsCommandsContext = c.Resolve<ITranslationsCommandsContext>();
return new CommandBus(CreateHandlersFactory);
})
.As<ICommandBus>().InstancePerRequest();
base.Load(builder);
}
private IHandleCommand CreateHandlersFactory(Type type)
{
if (type == typeof(XXXCommand))
{
return new XXXHandler(_commandsContext);
}
}
While the command bus looks like that
public class CommandBus : ICommandBus
{
private readonly Func<Type, IHandleCommand> _handlersFactory;
public CommandBus(Func<Type, IHandleCommand> handlersFactory)
{
_handlersFactory = handlersFactory;
}
public void SendCommand<T>(T command) where T : ICommand
{
var handler = (IHandleCommand<T>) _handlersFactory(typeof(T));
handler.Handle(command);
}
}
There is completely separate context used for translations for the app, but I do not thing that is important here.
I did not find any posts with similar problem. It only occurs when where two requests processed at the same time. I do not know if the configuration is wrong or Autofac messes things up, because it should not technically dispose dbcontext which was allocated for another request.
Sorry for the wall of text ;) I hope someone can help with that.
Obiously changing dbcontext's lifetime to SingleInstance fixed the problem, but we do not want that :)
SOLUTION EDIT:
As #ZeljkoVujaklija noticed CommandsDbContext declarations in InfrastractureModule seemed strange. I removed whole CommandBus registration from InfrastractureModule. Instead I created CommandsModule in the assembly where all the commands sit. It looks like that:
public class CommandsModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterAssemblyTypes(ThisAssembly)
.Where(x => x.IsAssignableTo<IHandleCommand>())
.AsImplementedInterfaces();
builder.Register<Func<Type, IHandleCommand>>(c =>
{
var ctx = c.Resolve<IComponentContext>();
return t =>
{
var handlerType = typeof(IHandleCommand<>).MakeGenericType(t);
return (IHandleCommand)ctx.Resolve(handlerType);
};
});
builder.RegisterType<CommandBus>()
.AsImplementedInterfaces();
}
}
Not only it fixes the problem but also gets rid of huge factory.
If you are running within ASP.NET Core you should run InstancePerLifetimeScope instead of InstancePerRequest
Use InstancePerLifetimeScope instead of InstancePerRequest. In previous ASP.NET integration you could register a dependency as InstancePerRequest which would ensure only one instance of the dependency would be created per HTTP request. This worked because Autofac was in charge of setting up the per-request lifetime scope. With the introduction of Microsoft.Extensions.DependencyInjection, the creation of per-request and other child lifetime scopes is now part of the conforming container provided by the framework, so all child lifetime scopes are treated equally - there’s no special “request level scope” anymore. Instead of registering your dependencies InstancePerRequest, use InstancePerLifetimeScope and you should get the same behavior. Note if you are creating your own lifetime scopes during web requests, you will get a new instance in these child scopes.
http://autofaccn.readthedocs.io/en/latest/integration/aspnetcore.html#differences-from-asp-net-classic

Dependency Injection Architectural Design - Service classes circular references

I have the following service classes:
public class JobService {
private UserService us;
public JobService (UserService us) {
this.us = us;
}
public void addJob(Job job) {
// needs to make a call to user service to update some user info
// similar dependency to the deleteUser method
}
}
public class UserService {
private JobService js;
public UserService(JobService js) {
this.js = js;
}
public void deleteUser(User u) {
using (TransactionScope scope = new TransactionScope()) {
List<IJob> jobs = jobService.findAllByUser(u.Id);
foreach (IJob job in jobs) {
js.deleteJob(job);
}
userDao.delete(user);
scope.Complete();
}
}
}
Each of these service classes is getting instantiated by IoC container, and there is not a functional problem, but this to me feels like there is a potential design flaw in this approach and I'm wondering if there's an alternative approach that makes more sense.
As someone already pointed out, the problem is not with limitations to the DI container but with your design.
I see the reason that you have a separate UserService and a JobService which contain a reference to each other. This is because both UserService and JobService contain some logic that needs the other service as a reference (adding a job requires adding a user, etc.). However, I think that you should NOT reference one service from the other. Rather, you should have another layer of abstraction behind the services which the services will use for the common logic. So, the services will contain the logic which can't(shouldn't) be reused and the helpers will contain the shared logic.
For example:
public class UserHelper{
//add all your common methods here
}
public class JobService {
private UserHelper us;
public JobService (UserHelper us) {
this.us = us;
}
public void addJob(Job job) {
// calls helper class
}
}
public class UserService {
public UserService(UserHelper js) {
this.js = js;
}
public void deleteUser(User u) {
// calls helper class
}
}
In this way, you won't have any issues with circular references and you will have one place which contains the logic which needs to be reused by different services.
Also, I prefer having services which are completely isolated from one another.
The problem you are having has in fact nothing to do with the limitations of your DI container, but it is a general problem. Even without any container, it will be impossible to create those types:
var job = new JobService([what goes here???]);
var user = new UserService(job);
The general answer is therefore to promote one of the dependencies to a property. This will break the dependency cycle:
var job = new JobService();
var user = new UserService(job);
// Use property injection
job.User = user;
Prevent however from using more properties than strictly needed. These dependency cycles should be pretty rare and makes it much harder to either wire your types together, or to validate the DI configuration for correctness. Constructor injection makes this much more easy.
You can decouple the services by using events. Instead of calling a dependent method of another service when an action has been performed, an event is raised. An integrator can then wire up the services through the events. A service does not even know the existence of the other service.
public class JobService
{
public event Action<User, Job> JobAdded;
public void AddJob(User user, Job job)
{
//TODO: Add job.
// Fire event
if (JobAdded != null) JobAdded(user, job);
}
internal void DeleteJobs(int userID)
{
//TODO: Delete jobs
}
}
public class UserService
{
public event Action<User> UserDeleted;
public void DeleteUser(User u)
{
//TODO: Delete User.
// Fire event
if (UserDeleted != null) UserDeleted(u);
}
public void UpdateUser(User user, Job job)
{
//TODO: Update user
}
}
The integrator wires up the services
public static class Services
{
public static JobService JobService { get; private set; }
public static UserService UserService { get; private set; }
static Services( )
{
JobService = new JobService();
UserService = new UserService();
JobService.JobAdded += JobService_JobAdded;
UserService.UserDeleted += UserService_UserDeleted;
}
private static void UserService_UserDeleted(User user)
{
JobService.DeleteJobs(user.ID);
}
private static void JobService_JobAdded(User user, Job job)
{
UserService.UpdateUser(user, job);
}
}
(Note: I simplified event raising a bit. It's not thread safe like this. But you can assume that the events are subscribed in advance and will not be changed later.)
This wont work in Autofac. See circular dependencies section of the documentation.
Constructor/Constructor Dependencies Two types with circular
constructor dependencies are not supported. You will get an exception
when you try to resolve types registered in this manner.
You could potentially use relationship types (Func<>, Lazy<>) to break the cycle.
Your code is a bit too generic to come up with a proper solution but you should consider changing the direction of dependencies regardless of what IoC container you use.
public class JobService {
private UserService us;
public JobService (UserService us) {
this.us = us;
}
public void addJob(Job job) {
// needs to make a call to user service to update some user info
}
}
public class UserService {
private JobService js;
public UserService(Func<JobService> jsFactory) {
this.js = jsFactory(this);
}
public void deleteUser(User u) {
// needs to call the job service to delete all the user's jobs
}
}
Alternatively, In the case of your example you could move deleteUser and create a method, delete all jobs on the job service and instead of refering to the user use an id. this breaks the dependency by using the id.
Another alternative is to pass the job service as a parameter to deleteUser.

Implementing just a little IOC for MVC 3

I'm working on a design that will allow me to mock out my database so I can test my views. I don't want to read a full book on IOC because I don't have the time right now. So, this is my home cooking.
Controller:
public ActionResult Milestone()
{
var result = SJMServiceFactory.GetService("Milestone");
return View(result);
}
Factory:
public static class SJMServiceFactory
{
public static DatabaseCollection_Result<T> GetService(string serviceName)
{
switch(serviceName)
{
case("Milestone"): return MileStoneService.GetMilestone();
case ("MilestoneMock"): return MileStoneService.GetMilestone(true);
default : return default(T);
}
}
}
MileStone
public class MileStoneService
{
public MileStoneService()
{
}
public static DatabaseCollection_Result<Milestone> GetMilestone(bool Mock)
{
if (Mock)
{
DatabaseCollection_Result<Milestone> mileStones = new DatabaseCollection_Result<Milestone>();
Milestone milestone1 = new Milestone();
milestone1.Name = "New";
Milestone milestone2 = new Milestone();
milestone2.Name = "Assessment";
mileStones.Results.Add(milestone1);
mileStones.Results.Add(milestone2);
return mileStones;
}
else
return null;
}
}
I figure I need to return an interface from my factory instead of that Generic type I tried and failed at doing. I don't know how to create an interface that works for all my models, is that the wrong direction?
Without reading a whole book (does one exist? IoC is a pretty small topic in the scheme of things):
Controller:
private readonly IMilestoneService milestoneSerivce;
public MilestoneController(IMilestoneService milestoneService)
{
this.milestoneService = milestoneService;
}
public ActionResult Milestone()
{
var result = milestoneService.GetMilestones();
return View(result);
}
IMilestoneService.cs
public interface IMilestoneService
{
DatabaseCollection_Result<Milestone> GetMilestones();
}
MilestoneService.cs
public class MilestoneService : IMilestoneService
{
public DatabaseCollection_Result<Milestone> GetMilestones()
{
return null;
}
}
MockMilestoneService.cs:
public class MockMilestoneService : IMilestoneService
{
public DatabaseCollection_Result<Milestone> GetMilestones()
{
DatabaseCollection_Result<Milestone> mileStones = new DatabaseCollection_Result<Milestone>();
Milestone milestone1 = new Milestone();
milestone1.Name = "New";
Milestone milestone2 = new Milestone();
milestone2.Name = "Assessment";
mileStones.Results.Add(milestone1);
mileStones.Results.Add(milestone2);
return mileStones;
}
}
Global.asax:
ObjectFactory.Configure(x => {
x.For<IMilestoneService>().Use<MilestoneService>();
// uncomment for test
//x.For<IMilestoneService>().Use<MockMilestoneService>();
});
This uses StructureMap, but I imagine the Ninject way to wiring up the dependencies is similar. Having never used Ninject I don't know for sure, but it looks like it might be something like:
Bind<IMilestoneService>().To<MilestoneService>();
In general though I wouldn't go about creating a whole new class to test your Views, I would use a mocking framework such as Moq to create mock objects and pass them to the View and then use Assertions about the ViewResult to determine if it worked correctly.
If you're doing interactive testing though and want to be detached from the database, this might be an ok approach.
Don't fear the learning curve. IoC is a reasonably simple concept.
Ninject was the first container I picked up, and it went smoothly. The only point I really struggled with for any amount of time was how to organize all the bindings, but even that was only an issue in large applications.
YMMV, but I'd say just diving in with Ninject or similar is better investment of time than DIY.
IoC with Ninject only takes code in a few places.
1: Bind you interfaces to implementations:
public class ServiceModule : NinjectModule
{
public override void Load() {
Bind<Common.Billing.AuthorizeNet.IBillingGatewayParametersFactory>().To<AuthorizeNetParameterFactory>();
Bind<Common.Billing.IBillingGateway>().To<Common.Billing.AuthorizeNet.BillingGateway>();
}
}
2: Use constructor arguments to pass dependencies into a class:
public class BillPayingService
{
private readonly IBillingGateway _billingGateway;
public BillPayingService(
IBillingGateway billingGateway
)
{
_billingGateway = billingGateway;
}
public void PayBills()
{
// ....
}
}
3: Initialize your container on application startup:
public static class Ioc
{
public static void Initialize()
{
var modules = new INinjectModule[] {
new ServicesModule(),
new DataModule()
new VideoProcessing.NinjectModule()
};
IKernel kernel = new Ninject.StandardKernel(modules);
}
}

Unity (dependency injection): How to pass in a parameter to the constructor in RegisterType

Can anyone help?
I have a wpf app (shouldn't matter) and in the Onstart i have my bootstrap stuff.. Its like this..
// Create unity container my service and repository
container = new UnityContainer()
.RegisterType<ISecurityRepository, SecurityRepository>()
.RegisterType<ISecurityService, SecurityService>();
Basically ISecurityService expects me to pass in a ISecurityRepository, hence the above fails.
But i am little confused, do i have to create a new IsecurityRespository and then pass it in, this defeats the object doesn't it?
Is there anyway i say "pass into SecurityService the ISecurityRepository from the container", but it hasn't been built yet?
Any ideas?
You don't have to create instances first. It all just works. That's the magic of IoC Containers.
Example:
public interface ISecurityService { }
public interface ISecurityRepository { }
public class SecurityService : ISecurityService
{
public SecurityService(ISecurityRepository repository)
{
Console.WriteLine("SecurityService created");
Console.WriteLine("Repository is " + repository);
}
public override string ToString()
{
return "A SecurityService";
}
}
public class SecurityRepository : ISecurityRepository
{
public SecurityRepository()
{
Console.WriteLine("SecurityRepository created");
}
public override string ToString()
{
return "A SecurityRepository";
}
}
public class MyClassThatNeedsSecurity
{
public MyClassThatNeedsSecurity(ISecurityService security)
{
Console.WriteLine("My class has security: " + security);
}
}
class Program
{
static void Main()
{
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType<ISecurityRepository, SecurityRepository>()
.RegisterType<ISecurityService, SecurityService>();
MyClassThatNeedsSecurity myClass =
container.Resolve<MyClassThatNeedsSecurity>();
}
}
}
This will print:
SecurityRepository created
SecurityService created
Repository is A SecurityRepository
My class has security: A SecurityService
You have a number of options, such as pre-creating your instances (as you showed in your follow-up post) or extending the lifetime of injected dependencies so that they're not recreated every time they're needed. But for the base case, this will work.
here is some more information. The constructor of my class is
public SecurityService(ISecurityRepository repository)
: base(repository)
{
}
After playing around a little bit, i managed to do the following but this causes me to create instances FIRST ... It seems to work.., but its an alternative.
// Create unity container my service and repository
ISecurityRepository securityRepository = new SecurityRepository();
ISecurityService securityService = new SecurityService(securityRepository);
container = new UnityContainer();
container.RegisterInstance<ISecurityRepository>(securityRepository);
container.RegisterInstance<ISecurityService>(securityService);

Categories