开发者

Create Object using ObjectBuilder

Want to create objects usin开发者_StackOverflow中文版g ObjectBuilder or ObjectBuilder2.

I do not want to use StructureMap

I was able to create the object having parameterless constructor using the code mentioned below.

 public class ObjectFactory : BuilderBase<BuilderStage>
    {
        public static T BuildUp<T>()
        {
            var builder = new Builder();

            var locator = new Locator { { typeof(ILifetimeContainer), new LifetimeContainer() } };

            var buildUp = builder.BuildUp<T>(locator, null, null);
            return buildUp;
        }

for creating object of customer you just call

ObjectFactory.BuildUp<Customer>

However this creates object of class which has no parameters, however I need to create object which are having constructor with parameters.


Used the CreateNew Attribute class to build the object and that worked fine. Also used the SessionStateBindingStrategry so that the object could take session variables as parameters in the constructor.

  public static T BuildUp<T>()
            {
                var locator = new Locator { { typeof(ILifetimeContainer), new LifetimeContainer() } };
//For accessing the session variables through StateValue<>
                 locator.Add(new DependencyResolutionLocatorKey(typeof(ISessionStateLocatorService), null), new SessionStateLocatorService());

                var builder = new Builder();

                var attribute = new CreateNewAttribute();
                IParameter parameter = attribute.CreateParameter(typeof (T));

                builder.Strategies.AddNew<SessionStateBindingStrategy>(BuilderStage.PreCreation);

                var builderContext = 
                    new BuilderContext(builder.Strategies.MakeStrategyChain(),locator,builder.Policies);
                object value = parameter.GetValue(builderContext);

                return (T)value;
            }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜